[英]How to calculate the highest, lowest and average number from a List?
cpuSensorValues.Add(sensor.Value);
if (cpuSensorValues.Count == 300)
{
for (int i = 0; i < cpuSensorValues.Count; i++)
{
Logger.Write("The Current CPU Temperature Is ===> " + sensor.Value);
}
cpuSensorValues = new List<float?>();
}
I'm adding to the List<float?> cpuSensorValues
every second a value.我
List<float?> cpuSensorValues
都会向List<float?> cpuSensorValues
添加一个值。 Then when it's getting to 300 values I want to calculate the highest number the lowest number and the average number from the List write each number to the logger and then to make a new instance to the List.然后当它达到 300 个值时,我想计算列表中的最高数字、最低数字和平均数字,将每个数字写入记录器,然后在列表中创建一个新实例。
The problem is how can I calculate these 3 numbers?问题是我如何计算这 3 个数字?
You could use Enumerable.Max()
, Enumerable.Min()
, and Enumerable.Average()
:您可以使用
Enumerable.Max()
、 Enumerable.Min()
和Enumerable.Average()
:
var min = cpuSensorValues.Min();
var max = cpuSensorValues.Max();
var avg = cpuSensorValues.Average();
However, this will enumerate the list 3 times (once per call).但是,这将枚举列表 3 次(每次调用一次)。 In practice, that's likely not going to be a problem, but if it is, you could just handle this yourself:
在实践中,这可能不会成为问题,但如果是,您可以自己处理:
// Returns min/max/average, ignoring null elements
Tuple<float,float,float> ComputeStats(IEnumerable<float?> values)
{
float min = float.MaxValue;
float max = float.MinValue;
float total = 0.0;
int count = 0;
foreach(var value in values)
{
if (value.HasValue)
{
min = Math.Min(min, value.Value);
max = Math.Max(max, value.Value);
total += value.Value;
++count;
}
}
return Tuple.Create(min, max, total / count);
}
Given that you're adding the values to the list yourself - you could even keep a running total + min and max as you go.鉴于您自己将值添加到列表中 - 您甚至可以随时保持运行总计 + 最小值和最大值。 This would completely avoid needing to enumerate (or even store) the values.
这将完全避免需要枚举(甚至存储)值。 The code above could easily be modified to handle this without storing the values in a
List<T>
at all.可以很容易地修改上面的代码来处理这个问题,而无需将值存储在
List<T>
中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.