简体   繁体   中英

How to filter List<T> and find average to make a distinct List<T>

How can I filter a list into distinct values by a specific field and where the values weren't distinct take their averages. Please see example

{
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);

Aim is to have a list with:

_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))
}

For any arbitrary values and quantity of entries

I have tried the following

            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;
            }

I know this is wrong but I cant seem to figure out the logic to modifying a list, I think creating a new list and appending in a forloop maybe the way forward but I cant work it out. I think Linq may help, but not too experienced with Lambda expressions. Thanks in advance

You can accomplish this using Linq, group your records by Time and use the Average function to compute the values for Voltage and Current for the Time groups:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM