Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading