Getting average value of groups with LINQ

后端 未结 2 1462
轮回少年
轮回少年 2020-12-19 12:42

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

相关标签:
2条回答
  • 2020-12-19 13:25

    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 group
    • Avg, which is the average GPA of the group

    Just "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:

    enter image description here

    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)

    0 讨论(0)
  • 2020-12-19 13:25

    Check this out:

    students.GroupBy(s => s.Level, s => s.GPA, 
                    (level, scores) => new { Level = level, Avg = scores.Average() }
    
    0 讨论(0)
提交回复
热议问题