如何通过特定字段将列表过滤为不同的值,并且在值不不同的情况下取平均值。请参阅示例{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 回答
慕盖茨4494581
TA贡献1850条经验 获得超11个赞
您可以使用 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)
});
- 1 回答
- 0 关注
- 86 浏览
添加回答
举报
0/150
提交
取消