有一类
public class human:IComparable<human>
{
double salary;
public double GetSalaryDollars()
{
return salary * 3;
}
int IComparable<human>.CompareTo(human other)
{
return salary.CompareTo(other.salary);
}
}
这个类有一定的对象集合(我省略了初始化)
List<human> mas = new List<human>();
因此,mas.Sort();我将按参数对我的集合进行排序salary,即 默认情况下,因为 这就是我实现接口的方式IComparable。问题是如何按给定参数排序?那些。如果我想按参数排序salary,我会这样写:
mas.Sort(salary);
如果我想按参数排序GetSalaryDollars(),我会这样写:
mas.Sort(GetSalaryDollars());
总之,让我的排序可以灵活一些,让我自己选择按哪个参数排序。如何才能做到这一点?也许以某种方式使用 lambda 表达式?
要按任意参数排序,请使用该方法的变体
List<T>.Sort Method (Comparison<T>):您可以使用lambda 表达式代替委托,但这已经是个人喜好问题了:
此方法的优点是您不必在结构中实现 IComparable 接口。一般来说,在委托代码中,你可以使用任何代码和任何数据,包括那些没有包含在结构数据中的
human。这对于调整排序方向也很有用。例如,作为要排序的数据,您可以这样写:So the "chosen ones" will float to the top of the list or go to the bottom, depending on the value of the flag
chosenOnesDown, while they themselveshumando not know who is elected and who is not.如果你想使用外部无法访问的结构的内部数据来比较结构,那么你可以从结构中暴露适当的方法: