.Take(5)在ObservableCollection上返回0的计数

时间:2011-04-26 13:47:55

标签: c# linq ienumerable take

我正在尝试使用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; }
    }
}

enter image description here

编辑:上传的实际代码

1 个答案:

答案 0 :(得分:3)

如果集合中没有数据,Take将不返回任何项目。如果实际上有一些数据,你必须在你没有向我们展示的代码中犯了一些错误。记住:选择不会破坏......

顺便说一下,还有一个Reverse,而不是Skip(Count - x).Take(x)