我正在尝试使用LINQ从ObservableCollection<PingReply>
返回前5个ping结果,但结果IEnumerable
的计数为0。
有人可以解释为什么lastFive
应用于.Take(5)
时,下面代码中的PingReplies
对象会返回0的计数吗?
发送ping时,PingReplies
集合获取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>();
PingReplies.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; }
}
}
编辑:上传的实际代码
答案 0 :(得分:3)
如果集合中没有数据,Take
将不返回任何项目。如果实际上有一些数据,你必须在你没有向我们展示的代码中犯了一些错误。记住:选择不会破坏......
Reverse
,而不是Skip(Count - x).Take(x)
。