user3113376
user3113376

Reputation: 171

Using an OrderBy after GroupBy in LINQ

I have a group of students, and I want to group them by their class level, like Freshman, Sophomore, Junior, Senior. And then I want to order them by GPA.

So if I just wanted to get the student with the best GPA, my potential result set would be something like:

Freshman - Name: James GPA : 3.9 
Sophomore - Name: Jessie GPA : 4.0
Junior - Name: Caitlyn GPA: 3.9
Senior - Name: Joshua GPA: 3.95

I've tried something like this:

var result = students.GroupBy(x => x.Level).OrderByDescending(x => x.GPA).Take(count).ToList();

but it always breaks and I don't quite know how to fix it. I've tried putting a Select between them and moving the OrderBy in the Select but I couldn't get it working either.

Upvotes: 0

Views: 139

Answers (1)

Selman Genç
Selman Genç

Reputation: 101731

If you wanna get the student who has the biggest GPA from each group you can use:

students.GroupBy(x => x.Level)
      .Select(g => g.First(x => x.GPA == g.Max(y => y.GPA)))
      .Take(count).ToList();

You can also use a third-party library method MaxBy to do that more efficiently

students.GroupBy(x => x.Level)
          .Select(g => g.MaxBy(x => x.GPA))
          .Take(count).ToList();

Upvotes: 1

Related Questions