Search code examples
c#linqlambdagroup-bymax

Using LinQ Lambda expressions in C#, how to select collection of objects with maximum field value?


given following class:

    public class Duo
    {
        public int Iteration { get; set; }
        public string Name { get; set; }
    }

and collection like this:

List<Duo> list = new List<Duo>() { 
    new Duo () {Name = "A", Iteration = 1},
    new Duo () {Name = "B", Iteration = 1},
    new Duo () {Name = "C", Iteration = 2},
    new Duo () {Name = "D", Iteration = 2}
};

using LinQ lambda expression, how do I get a collection of objects where Iteration is the max value in the collection? From this example I expect to get a collection with C & D, because 2 is the highest value for Iteration field.

Following works: var items = list.Where(x => x.Iteration == list.Max(y => y.Iteration)); but it iterates through the collection twice, which is not ideal. I was told I should use GroupBy but I'm not sure how. Any advice?


Solution

  • You could group by the iteration and then order (here descending) by key and pick the first group:

    var res = list
        .GroupBy(x => x.Iteration)
        .OrderByDescending(x => x.Key)
        .First()
        .ToList();