为何C# Linq中ThenByDescending在特定排序场景下无效果?
为何Linq中OrderByDescending后调用ThenByDescending无效果?
核心差异在于Linq排序中主排序键与次要排序键的生效逻辑:
Linq里的OrderBy/OrderByDescending是设置主排序键,而ThenBy/ThenByDescending是设置次要排序键——只有当两个元素的主排序键完全相等时,次要排序键才会参与排序,用来区分主键相同的元素顺序。
第一段代码分析
using System; using System.Linq; using System.Collections.Generic; public class Program { public static void Main() { var numbers = new List<int>() { 3, 7, 1, 5, 4, 6, 2 }; var sortedNumbers = numbers.OrderByDescending(x => x); foreach (int i in sortedNumbers ) { Console.WriteLine(i); } var sortedNumbers1 = sortedNumbers.ThenByDescending(x => x % 2 == 0); foreach (int i in sortedNumbers1 ) { Console.WriteLine(i); } } }
这段代码先按数值降序排序,得到序列7,5,3,1,6,4,2。这里每个元素的主排序键(数值)都是唯一的,没有任何两个元素的主键值相同。后续调用ThenByDescending(x => x%2==0)时,次要排序键没有生效场景——所有元素主排序键都不一样,Linq不会去比较次要键,最终序列和之前完全一致。
第二段代码分析
using System; using System.Linq; using System.Collections.Generic; public class Program { public static void Main() { var numbers = new List<int>() { 3, 7, 1, 5, 4, 6, 2 }; var sortedNumbers = numbers.OrderByDescending(x => x % 2 == 0); foreach (int i in sortedNumbers ) { Console.WriteLine(i); } Console.WriteLine("*-******************"); var sortedNumbers1 = sortedNumbers.ThenByDescending(x => x); foreach (int i in sortedNumbers1 ) { Console.WriteLine(i); } } }
这段代码先按是否为偶数降序排序:bool类型排序时true(偶数)优先级高于false(奇数),初始排序结果是偶数在前(原列表顺序4,6,2)、奇数在后(原列表顺序3,7,1,5)。此时所有偶数的主排序键都是true,所有奇数的主排序键都是false——同一组内元素主键相同,ThenByDescending(x => x)就会生效:偶数组按数值降序变为6,4,2,奇数组按数值降序变为7,5,3,1,最终排序效果符合预期。
内容的提问来源于stack exchange,提问作者rahularyansharma
相关产品推荐
相关产品推荐

