I have a mock application where an inheritance chain like
Employee,Manager,President
etc.
The Employee class looks like
class Employee
{
Quick and perhaps dirtier solution that works:
return managerList
.OrderByDescending(x => x.EmployeesManaged.Count)
.FirstOrDefault();
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;
}
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?
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.