Search code examples
c#linq

LINQ Select min field value from multiple similar records in List<T>


I am trying to figure out how to do what I know in T-SQL as a group and aggregate process.

I have a List<T> and in that list I have 2 records of each instance. I need the record with the lower value.

So in application I have student records. So my list would be like this:

0    studentid 1    score 75.345
1    studentid 1    score 33.653
2    studentid 2    score 94.876
3    studentid 2    score 15.234
etc....

I have these records in a List<Student> result:

var result = abc.Find<Student>...snip

To be clear, the business rule says to find the lower score between the two.

So how would I accomplish this filtering and selection in Linq? I see there are Group and aggregate Linq extensions but honestly not sure if that is the route to pursue.


Solution

  • Use the GroupBy and Min functions.

    var result = context.GroupBy(s=> s.StudentId)
                        .Select(sg => new {
                                            StudentId = sg.Key, 
                                            MinScore = sg.Min(sc=> sc.Score)
                                          });