I'm trying to use LINQ to return the top 5 ping results from an ObservableCollection<PingReply>
but the resulting IEnumerable
has a count of 0.
Can anyone explain why the lastFive
object in the code below returns a count of 0 when .Take(5)
is applied to PingReplies
?
When a ping is sent, the PingReplies
collection get's that object in the ObservableCollection
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.Collections.ObjectModel;
namespace XXX.ServerMonitor.Servers
{
class WindowsServer : IServer
{
public WindowsServer(string address)
{
this.Address = address;
PingReplies = new ObservableCollection<PingReply>();
PingR开发者_运维知识库eplies.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(PingReplies_CollectionChanged);
}
void PingReplies_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
IEnumerable<PingReply> lastFive = PingReplies.Take(5);
if (lastFive.Where(a => a.Status != IPStatus.Success).Count() == 5)
{
// 5 failed attempts
// Server may be down
Console.WriteLine(Address + " may be down");
}
}
}
public ObservableCollection<PingReply> PingReplies { get; set; }
PingReply IServer.Ping()
{
PingReply reply = Utils.Ping.Send(this.Address);
PingReplies.Add(reply);
return reply;
}
public string Address { get; set; }
}
}
Edit: Actual code uploaded
If there is no data in the collection, Take
returns no items. If there is actually some data around, you must have made some mistake in code you aren't showing us. Remember: select ain't broken ...
by the way, there is also a Reverse
, instead of Skip(Count - x).Take(x)
.
精彩评论