Find max count of a list of custom types

后端 未结 4 2055
耶瑟儿~
耶瑟儿~ 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:19

    I think this might be what you want:

    public static Manager GetBestManager(this IList managerList) {
        Func 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?

提交回复
热议问题