2

我正在尝试使用 LINQ 从 an 返回前 5 个 ping 结果,ObservableCollection<PingReply>但结果IEnumerable的计数为 0。

谁能解释为什么下面代码中的对象在应用于lastFive时返回计数 0 ?.Take(5)PingReplies

发送 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; }
    }
}

在此处输入图像描述

编辑:上传的实际代码

4

1 回答 1

3

如果集合中没有数据,Take则不返回任何项目。如果周围确实有一些数据,那么您一定在没有向我们展示的代码中犯了一些错误。记住:选择没有坏...

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

于 2011-04-26T16:27:47.727 回答