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

LINQ – aggregate function inside nested loop

I have the following object structure.

public class FirstClass
{
    public string EmployeeNo { get; set; }

    public List<SecondClass> SecondClass { get; set; }
}

public class SecondClass
{
    public int Count { get; set; }
}

My following code is returning me an error.

var result = FirstClass.Where(fc => fc.SecondClass.Aggregate((item1, item2) => item1.Count > item2.Count ? item1 : item2));

I am getting the following error.

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

Cannot implicitly convert type of "SecondClass" into bool

How can I use return the FirstClass object to have the highest count from SecondClass?

>Solution :

You can select the count of each item in SecondClass and use Max to find the maximum value. Then you select this value of each item in FirstClass and use Max again:

int highestCount = input.Select(x => x.SecondClass.Select(y => y.Count).Max()).Max();

If you want to find the item with the highest count, you can replace the first Select by OrderByDescending and the second Max by FirstOrDefault:

var itemWithHighestCount = input.OrderByDescending(x => x.SecondClass.Select(y => y.Count).Max()).FirstOrDefault();

Online demo: https://dotnetfiddle.net/0rWARC

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