C#排序Lambda,返回什么
本文关键字:返回 什么 Lambda 排序 | 更新日期: 2023-09-27 17:57:41
我在网上的评分很低,我找不到简单的答案。
我应该在List<T>.Sort()
上返回什么?Is是索引或移位(如Java)
我的代码:
newUsers.Sort((userB, userA) => {
// User pos -1 means they have no pos.
if (userA.pos == -1 && userB.pos == -1) {
return 0;
}
if (userA.pos == -1) {
return -1;
}
if (userB.pos == -1) {
return 1;
}
if (userA.pos < userB.pos) {
return 1;
} else {
return -1;
}
}
);
Comparison Delegate的MSDN文档返回一个System.Int32:
public delegate int Comparison<in T>(
T x,
T y
)
一个带符号的整数,表示x和y的相对值,如下表所示。
Value | Meaning
--------------------------------------
Less than 0 | x is less than y.
0 | x equals y.
Greater than 0 | x is greater than y.
在您的琐碎情况下,如果您不确定该做什么,并且由于您只比较pos
,您可以使用:
newUsers.Sort((userA, userB) => {
userA.pos.CompareTo(userB.pos);
}
);
这将为你完成全部工作。
您有3个选择:
- 左值小于右值:小于0
- 左值大于右值:大于0
- 值相等:0
示例:
int x1 = 1;
int x2 = 2;
int res1 = Comparer<int>.Default.Compare(x1,x2); //-1 (1<2)
int res2 = Comparer<int>.Default.Compare(x2, x1); //1 (2>1)
int res3 = Comparer<int>.Default.Compare(x1, x1); //0 (1=1)
您也可以使用任何其他值< 0
(或任何正值> 0
而不是1
)来代替-1
,以获得相同的结果,但这三个值是常用的。
从这个值开始,Sort()
方法会排列列表的排序顺序。