OrderBy的特例

kam*_*ame 5 c# linq sorting

是什么

.OrderBy(x => x == somevalue)
Run Code Online (Sandbox Code Playgroud)

做?它将一些值元素排序到最后.但为什么呢?

代码示例:

var arr = new int[] { 1, 2, 3 };
var arr2 = arr.OrderBy(x => x == 2).ToArray();
// arr2 --> 1, 3, 2
Run Code Online (Sandbox Code Playgroud)

Dmi*_*nko 17

你是按顺序排序的bool,因为它x == 2是一个bool值(true如果是x == 2,false否则).如果是bool(bool工具IComparable<bool>)

https://msdn.microsoft.com/en-us/library/kf07t5s5(v=vs.110).aspx

 false < true
Run Code Online (Sandbox Code Playgroud)

这就是为什么

 OrderBy(x => x == 2)
Run Code Online (Sandbox Code Playgroud)

的意思是"是第一值等于22的".

 {1, 2, 3} -> {1, 3, 2}
Run Code Online (Sandbox Code Playgroud)

编辑:最后,OrderBy是一个稳定的排序,这就是保留初始顺序1, ..., 3(1之前3)的原因(如果你使用不稳定的排序算法对数组进行排序,比如,你可以得到快速排序{3, 1, 2})