First, there's no need to have an IComparer<Employee>
that sorts by descending if your Employee
class implements IComparable<Employee>
using the same sort criteria. And it's horribly inefficient for your Employee
class to instantiate a new IComparer<Employee>
for every comparision.
You should change your Employee
class so that its CompareTo
looks like this:
int CompareTo(Employee next)
{
return next.NumberOfKids.CompareTo(this.NumberOfKids);
}
Then you can ditch the EmployeeComparer
altogether and sort like this:
list = list.Take(3).ToList();
list.Sort(); // Uses default IComparable for the Employee class
return list;
Typically, you make the IComparable<T>
implementation on the class perform the default sorting order. In the case of employees, that'd probably either be by employee ID or perhaps last name, first name. IComparer<T>
implementations should be for other sorting criteria.
With List<T>
, though, you have another option: use an anonymous function. For example, you could do this by writing:
list.Sort((x, y) => y.NumberOfKids.CompareTo(x.NumberOfKids));
See this List.Sort overload.
Or, you could just ditch the whole idea of IComparer<T>
and IComparable<T>
and List.Sort
altogether and do it the LINQ way:
var result = list.Take(3).OrderByDescending(x => x.NumberOfKids).ToList();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…