如何通過特定字段將列表過濾為不同的值,并且在值不不同的情況下取平均值。請參閱示例{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);目標是列出一個包含以下內(nèi)容的列表:_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))}對于任意值和條目數(shù)量我嘗試過以下方法 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; }我知道這是錯誤的,但我似乎無法弄清楚修改列表的邏輯,我認為創(chuàng)建一個新列表并附加到 forloop 中可能是前進的方向,但我無法解決。我認為 Linq 可能會有所幫助,但對 Lambda 表達式不太有經(jīng)驗。提前致謝
如何過濾 List<T> 并查找平均值以生成不同的 List<T>
慕田峪7331174
2023-08-20 11:10:31