I’ll show you how to use LINQ to objects to find the maximum item in each group.
Consider this scenario: I have a list of students in this case, along with their grades and marks. Our aim is to determine the student, grade, and there max marks in each group.
- First Group by the
Grade
- Then sort each group by
Marks
in descending order - Then take first of each group
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Grade { get; set; }
public int Marks { get; set; }
}
void Main(string[] args)
{
var students = new List<Student>(){
new Student{Id=1,Name="John",Grade="I",Marks=10},
new Student{Id=2,Name="Jane",Grade="II",Marks=80},
new Student{Id=3,Name="Jack",Grade="III",Marks=50},
new Student{Id=4,Name="Lee",Grade="VI",Marks=60},
new Student{Id=5,Name="Tin",Grade="II",Marks=50},
new Student{Id=6,Name="Santosh",Grade="VII",Marks=40},
new Student{Id=7,Name="Bill",Grade="II",Marks=60},
new Student{Id=8,Name="Jonson",Grade="VI",Marks=91},
new Student{Id=9,Name="Jason",Grade="VI",Marks=92},
new Student{Id=10,Name="Steve",Grade="III",Marks=72},
new Student{Id=11,Name="Prem",Grade="VII",Marks=40},
new Student{Id=12,Name="Test",Grade="VII",Marks=30},
new Student{Id=13,Name="Dove",Grade="I",Marks=20},
};
var results = students.GroupBy(s => s.Grade)
.Select(d => d.OrderByDescending(d => d.Marks))
.Select(d => d.First());
foreach (var student in results)
{
Console.WriteLine(student);
}
}