Find max count of a list of custom types

后端 未结 4 2054
耶瑟儿~
耶瑟儿~ 2021-01-24 12:03

I have a mock application where an inheritance chain like Employee,Manager,President etc.

The Employee class looks like

class Employee
    {         


        
相关标签:
4条回答
  • 2021-01-24 12:07

    Quick and perhaps dirtier solution that works:

    return managerList
           .OrderByDescending(x => x.EmployeesManaged.Count)
           .FirstOrDefault();
    
    0 讨论(0)
  • 2021-01-24 12:14

    1) It depends on where the data is coming from. A database, file from disk, in memory collection. Often the List or whatever structure is determined by the source.

    2) Your LINQ is getting the max number, not the Manager with the highest count. Try:

    public static Manager GetBestManager(List<Manager> managerList)
    {
        Manager m = managerList.OrderByDescending(x => x.EmployeesManaged.Count).First();
        return m;
    }
    
    0 讨论(0)
  • 2021-01-24 12:19

    I think this might be what you want:

    public static Manager GetBestManager(this IList<Manager> managerList) {
        Func<Manager, int> getCount=x => x.EmployeesManaged.Count;
        return managerList.First(x => getCount(x)==managerList.Max(getCount));
    }
    

    If there're more than one manager have the same count of employees, this return the first one. The reason FirstOrDefault is not used, is because the max value is fetched from the list, we can always find a manager matches the max value except the collection is empty.

    So, why use FirstOrDefault to return null rather than throw the exception to let the caller knows who passed an empty list?

    0 讨论(0)
  • 2021-01-24 12:20

    see my answer on this post: How can I get LINQ to return the object which has the max value for a given property?

    You can use the Aggregate function in System.Linq

    Aggregate is faster because it simply runs through the collection once and takes the biggest as it goes. OrderBy essentially has to do a bubble sort which is more costly.

    0 讨论(0)
提交回复
热议问题