平均数组 C# WPF 中的所有 PingReply RoundTripTime

Average all PingReply RoundTripTime in array C# WPF

我正在使用 C# WPF 编写一个新程序,其中一部分包括对 10 PingReply.RoundTripTime 取平均值并将其除以 2 以求出单程行程时间。我把所有的PingReply个实例都放在一个数组中,arrayReply,现在要执行上面的操作。我已经尝试了很多东西,但这就是我现在所拥有的:

//New integer replyCount for counting ping replies
int replyCount = 0;
long Atime = 0;
long time = 0;

//for each PingReply instance in arrayReply
foreach (PingReply r in arrayReply)
{
    //set long integer (64-bit) Atime (time of ping) to the previous value of Atime
    //plus half of the next RoundTripTime divided by 2 (for approx one-way distance)
    long oneWayTime = r.RoundtripTime / 2;

    long x = Atime + oneWayTime;

    //add one to replyCount
    replyCount++;

    //Divide Atime by number of replies
    time = x / replyCount;
}

pingAverage.Text = time.ToString();

然而,这每次都会导致 0。我该如何解决这个问题?

使用 LINQ 求平均值:

var time = arrayReply.Average(pr => pr.RoundtripTime) / 2;