排序在C#中的列表(带有各种参数)参数、列表

2023-09-04 04:45:07 作者:厌烦

我有对象的列表。这个对象有不同的领域,例如年龄和名字

I have a list of objects. That objects have various field, e.g. age and name

现在有时我想对列表进行名称,有时按年龄排序。另外,有时为了增加,有时降序排列。

Now sometimes I'd like to sort the list by names and sometimes by age. Additional sometimes increasing order and sometimes decreasing order.

现在我明白了,我应该实现我的目标Comparable接口并重写CompareTo方法。

Now I understand that i should implement the Comparable interface in my object and override the CompareTo method.

但我怎么能做到这一点时,我想,以支持各种排序命令?

But how can i do this when i want to support various sorting orders?

我是否必须设置排序顺序在我的对象或者是它在某种程度上可以通过排序方法调用传递的排列顺序?

Do i have to set the sorting order in my object or is it somehow possible to pass the sorting order by the sort method call?

推荐答案

方法调用可以做的一切;无需使用比较器:

The method call can do everything; no need for a comparer:

list.Sort((x,y)=>string.Compare(x.Name,y.Name));

list.Sort((x,y)=>y.Age.CompareTo(x.Age)); // desc
list.Sort((x,y)=>x.Age.CompareTo(y.Age)); // asc

请注意,二是降,通过交换比较X / Y。

Note the second is descending, by swapping x/y in the compare.