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.
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