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.
To better put it, I have a list of Students:
List<Student> students = new List<Student> {
new Student { Name="Bob", Level=Level.Sophomore, GPA=3.2f },
new Student { Name="Cathy", Level=Level.Freshman, GPA=3.6f },
new Student { Name="James", Level=Level.Senior, GPA=3.8f },
new Student { Name="Jessica", Level=Level.Senior, GPA=3.7f },
new Student { Name="Derek", Level=Level.Junior, GPA=2.8f },
new Student { Name="Sam", Level=Level.Junior, GPA=3.1f }
};
And I want to group them by their Class Level, so they'll be grouped into Freshman, Sophomore, Junior, and Senior. And then I want to be able to get the Average GPA for those groups.
So a possible result set for these students would be:
Senior: 3.7
Junior: 2.9
Sophomore: 3.2
Freshman : 3.6
I'm not quite too sure how to go about getting this result though. I have tried things like students.GroupBy(x => x.Level).Average();
but it does not work.
Any thoughts on this would be greatly appreciated. Thank you!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…