I am trying to split my List into different groups based on a certain value each item in the List has, and then find the average of another value in those groups.
T
You have to use an additional Select
, so you're looking for something like this:
var result = students.GroupBy(s => s.Level)
.Select(g => new {Level=g.Key, Avg=g.Average(s => s.GPA)});
Select(g => new {...})
creates an instance of a new anonymous type for each group.
That type has two properties:
Level
, which is the Key
property of the groupAvg
, which is the average GPA of the groupJust "imagine" there's this type in use (more or less):
class GroupAverage
{
public Level Level { get; set; }
public float Avg { get; set; }
}
var result = students.GroupBy(s => s.Level)
.Select(g => new GroupAverage { Level=g.Key, Avg=g.Average(s => s.GPA) } );
but it simply has no name.
result
is now:
Feel free to round the values if you need to.
To get the Level
with the highest average, simply use
var highest = result.OrderByDescending(a => a.Avg).First().Level;
(Note that this will crash if there are no items in students
)
Check this out:
students.GroupBy(s => s.Level, s => s.GPA,
(level, scores) => new { Level = level, Avg = scores.Average() }