【问题标题】:How to sort a list of int list如何对 int list 的列表进行排序
【发布时间】:2018-04-23 04:40:59
【问题描述】:

请告诉我如何对包含整数列表的列表进行排序。

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 });

如何对上面的 List 进行排序以获得以下结果?

 2, 3, 9
 2, 4, 7
 4, 7, 8
 6, 8, 9

提前谢谢你!

【问题讨论】:

  • 可以将比较列表的比较函数写成元素
  • 您的标准是什么?为什么 2,3,9 2,4,7?
  • 您的要求有点不清楚,因为您的父列表中的每个子列表都已排序。因此,您可以通过按每个列表中的第一个数字对列表进行排序来获得所需的结果:var result = numberLists.OrderBy(x =&gt; x[0]).ToList();。请澄清您的问题。
  • 大家好,抱歉,我不够具体。挑战是根据其元素对列表进行排序:首先按 [0] 次,然后按 [1] 次,最后按 [2] 次元素同时 TheGeneral 已经提供了我正在寻找的解决方案。

标签: c# sorting generics integer


【解决方案1】:

你可以这样做

var results = numberLists.OrderBy(x => x[0])
                         .ThenBy(x => x[1])
                         .ThenBy(x => x[2]);

foreach (var result in results)
{
   foreach (var subresult in result)
   {
      Console.Write(subresult + " ");
   }
   Console.WriteLine();
}

输出

2 3 9
2 4 7
4 7 8
6 8 9

Full Demo here


其他结果

Enumerable.OrderBy Method (IEnumerable, Func)

根据a按升序对序列中的元素进行排序 键。

Enumerable.ThenBy Method (IOrderedEnumerable, Func)

对序列中的元素进行后续排序 按key升序排列。

【讨论】:

  • 感谢您的解决方案。它有效,这正是我想要的。 ;)
  • @JánosZoltánKis 如果这解决了您的问题,请不要忘记投票并标记为正确
  • 我已经投票了,但是很遗憾我还没有达到 15 个声望,因此我的反馈是不可见的。 ¯_(ツ)_/¯
  • @JánosZoltánKis Ahh 好的,然后确保你按了勾,这会给你 2 声望
【解决方案2】:

您可以根据自己的标准以简单的方式进行操作

var sortedLists = numberLists.OrderBy(x => string.Join(",", x.ToArray())).ToList();

只需将其转换为字符串,然后作为字符串进行比较

【讨论】:

    猜你喜欢
    • 2013-07-03
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 2022-11-17
    • 2016-01-08
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    相关资源
    最近更新 更多