Search code examples
c#.netlinqmaxaggregate

How can I use LINQ to get the instance with the highest value of a property in a child list?


I have the following class structure:

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

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

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

I am using this code:

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

However, it results in this compiler error:

Cannot implicitly convert type of "SecondClass" into bool

How can I get the FirstClass object containing the SecondClass object with the highest value of the SecondClass.Count property? If multiple FirstClass objects have the same highest value it should return the first such object.


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