如何过滤List <T>并找到平均值以得出不同的List <T>

时间:2019-08-09 19:38:40

标签: c#

如何通过特定字段将列表过滤为不同的值,而值不同的地方取其平均值。请参阅示例

{
Public int Time;
Public float Voltage;
Public float Current;
Public Resistance(int time, float voltage, float current)
{
Time = time;
Voltage = voltage;
Current = current;
}
Public List<Resistance> _resistances = new List<Resistance>();
_resistances.Add(new Resistance(Time = 1, Voltage =3.2, Current = 1);
_resistances.Add(new Resistance(Time = 1, Voltage =4.0, Current = 2);
_resistances.Add(new Resistance(Time = 1, Voltage =6.5, Current = 6);
_resistances.Add(new Resistance(Time = 2, Voltage =3.2, Current =4);
_resistances.Add(new Resistance(Time =2, Voltage =3.2, Current = 2);
_resistances.Add(new Resistance(Time = 3, Voltage 5, Current = 1);

目标是列出以下内容:

_resistance[0]{ Time =1,, Voltage = Average(3.2,4,6.5), Current = Average(1,2,6))
_resistance[1]{ Time =2,, Voltage = Average(3.2,3.2,5), Current = Average(4,2,1))
}

对于任意值和条目数量

我尝试了以下

            int divisor = 1;
            double voltageSum = 0;
            double currentSum = 0;

            while (j >= 1)
            {
                while (_resistances[j].Time== _resistances[j - 1].Time)
                {
                    divisor++;
                    voltageSum += _resistances[j].Voltage;
                    currrentSum += _resistances[j].Current;
                    _resistances.RemoveAt(j);
                    j -= 1;
                }

                var averageVoltage = voltageSum / divisor;
                var averageCurrent = currentSum / divisor;
                _rawDataList[j].Voltage = (float)averageVoltage;
                _rawDataList[j].Current= (float)averageCurrent;
                j -= 1;
            }

我知道这是错误的,但是我似乎无法弄清楚修改列表的逻辑,我认为创建一个新列表并在forloop中追加可能是前进的方向,但我无法解决。我认为Linq可能会有所帮助,但对Lambda表达式的了解不是太丰富。预先感谢

1 个答案:

答案 0 :(得分:2)

您可以使用Linq完成此操作,按时间对记录进行分组,然后使用Average函数为时间组计算电压和电流值:

_resistances
 .GroupBy(r => r.Time)
 .Select(g => new { 
      Time = g.Key, 
      Voltage = g.Average(r => r.Voltage), 
      Current = g.Average(r => r.Current) 
 });