如何对List<List<int>>类型整数嵌套列表排序以得到指定结果?
对List<List>按字典序排序的实现方案
这其实就是按字典序对嵌套整数列表进行排序的需求,在C#里可以通过List<T>.Sort方法配合自定义比较逻辑轻松实现,下面给你两种常用的方案:
方案一:使用Lambda表达式快速实现
这种方式适合只需要单次使用排序逻辑的场景,代码简洁直接:
List<List<int>> numberLists = new List<List<int>>(); numberLists.Add(new List<int>() { 6, 8, 9 }); numberLists.Add(new List<int>() { 2, 4, 7 }); numberLists.Add(new List<int>() { 4, 7, 8 }); numberLists.Add(new List<int>() { 2, 3, 9 }); // 自定义排序逻辑 numberLists.Sort((listA, listB) => { // 遍历两个列表的对应元素,找到第一个不同的位置 int minCount = Math.Min(listA.Count, listB.Count); for (int i = 0; i < minCount; i++) { int compareResult = listA[i].CompareTo(listB[i]); if (compareResult != 0) { return compareResult; } } // 如果前面元素都相同,短列表排在前面(可选逻辑,根据需求调整) return listA.Count.CompareTo(listB.Count); }); // 验证输出 foreach (var list in numberLists) { Console.WriteLine(string.Join(", ", list)); }
逻辑说明
- 先逐个比较两个子列表的对应位置元素,第一个不同的元素的大小关系,就是整个子列表的排序依据;
- 如果两个子列表前面的元素完全相同(比如一个是
{2,3},另一个是{2,3,9}),则短列表排在前面(你可以根据自己的需求修改这部分逻辑)。
方案二:自定义IComparer<List>类(可复用)
如果你的项目中需要多次用到这种排序逻辑,推荐封装成一个比较器类,方便复用:
// 自定义比较器类 public class IntListComparer : IComparer<List<int>> { public int Compare(List<int> x, List<int> y) { // 处理null的情况(可选,根据你的业务场景调整) if (x == null && y == null) return 0; if (x == null) return -1; if (y == null) return 1; int minCount = Math.Min(x.Count, y.Count); for (int i = 0; i < minCount; i++) { int result = x[i].CompareTo(y[i]); if (result != 0) { return result; } } // 元素都相同时,按列表长度排序 return x.Count.CompareTo(y.Count); } } // 使用示例 List<List<int>> numberLists = new List<List<int>>(); numberLists.Add(new List<int>() { 6, 8, 9 }); numberLists.Add(new List<int>() { 2, 4, 7 }); numberLists.Add(new List<int>() { 4, 7, 8 }); numberLists.Add(new List<int>() { 2, 3, 9 }); numberLists.Sort(new IntListComparer()); // 输出验证 foreach (var list in numberLists) { Console.WriteLine(string.Join(", ", list)); }
两种方案运行后,都会得到你期望的结果:
2, 3, 9
2, 4, 7
4, 7, 8
6, 8, 9
内容的提问来源于stack exchange,提问作者János Zoltán Kis
相关产品推荐
相关产品推荐

