Linq order by,group by 和 order by 每个组? [英] Linq order by, group by and order by each group?

查看:37
本文介绍了Linq order by,group by 和 order by 每个组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的对象:

I have an object that looks something like this:

public class Student
{
    public string Name { get; set; } 
    public int Grade { get; set; }
}

我想创建以下查询:按学生姓名对成绩进行分组,按成绩对每个学生组进行排序,并按每组中的最高成绩对组进行排序.

I would like to create the following query: group grades by student name, order each student group by grades, and order groups by max grade in each group.

所以它看起来像这样:

A 100
A 80
B 80
B 50
B 40
C 70
C 30

我创建了以下查询:

StudentsGrades.GroupBy(student => student.Name)
    .OrderBy(studentGradesGroup => studentGradesGroup.Max(student => student.Grade));

但是那会返回 IEnumerable IGrouping,并且我无法在里面对列表进行排序,除非我在另一个 foreach 查询中这样做并且使用 AddRange 将结果添加到不同的列表.

But that returns IEnumerable IGrouping, and I have no way to sort the list inside, unless I do that in another foreach query and add the results to a different list using AddRange.

有没有更漂亮的方法来做到这一点?

Is there a prettier way to do that?

推荐答案

当然:

var query = grades.GroupBy(student => student.Name)
                  .Select(group => 
                        new { Name = group.Key,
                              Students = group.OrderByDescending(x => x.Grade) })
                  .OrderBy(group => group.Students.First().Grade);

请注意,您可以在订购后只获得每个组中的第一个等级,因为您已经知道第一个条目将获得最高等级.

Note that you can get away with just taking the first grade within each group after ordering, because you already know the first entry will be have the highest grade.

然后你可以用:

foreach (var group in query)
{
    Console.WriteLine("Group: {0}", group.Name);
    foreach (var student in group.Students)
    {
        Console.WriteLine("  {0}", student.Grade);
    }
}

这篇关于Linq order by,group by 和 order by 每个组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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