使用LINQ获取组的平均值 [英] Getting average value of groups with LINQ

查看:296
本文介绍了使用LINQ获取组的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据列表中每个项目具有的某个值将列表分为不同的组,然后找到这些组中另一个值的平均值.

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

我想按班级对他们进行分组,因此他们将被分为新生,大二,大三和大四.然后,我希望能够获得这些群体的平均GPA.

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

我不太确定如何获得此结果.我已经尝试过students.GroupBy(x => x.Level).Average();之类的东西,但是它不起作用.

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!

推荐答案

您必须使用其他Select,因此您正在寻找类似这样的东西:

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 {...})为每个组创建一个新的匿名类型的实例.


Select(g => new {...}) creates an instance of a new anonymous type for each group.

该类型具有两个属性:

  • Level,这是组的Key属性
  • Avg,这是该组的平均GPA
  • 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) } );

但是它根本没有名字.

result现在是:

如有需要,可以随意舍入这些值.

Feel free to round the values if you need to.

要获得具有最高平均值的Level,只需使用

To get the Level with the highest average, simply use

var highest = result.OrderByDescending(a => a.Avg).First().Level;

(请注意,如果students中没有任何项目,则会崩溃)

(Note that this will crash if there are no items in students)

这篇关于使用LINQ获取组的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆