【问题标题】:sort a list using a comparison list使用比较列表对列表进行排序
【发布时间】:2013-02-13 05:33:49
【问题描述】:

需要在c#中做这样的事情我在java中做:

Double[][] matrix = new Double[3][4];

        matrix[0][0] = 100.0;
        matrix[0][1] = -3.0;
        matrix[0][2] = 50.0;
        matrix[0][3] = 50.3;

        matrix[1][0] = 1.2;
        matrix[1][1] = 1.1;
        matrix[1][2] = 0.9;
        matrix[1][3] = 10000.0;

        matrix[2][0] = 2.3;
        matrix[2][1] = 2.35;
        matrix[2][2] = 2.32;
        matrix[2][3] = 2.299;

        Arrays.sort(matrix, new Lexical());

我一直在看 MSDN 文档,除了排序 List 没有其他方法,List<List<T>> 没有任何东西。

谢谢

【问题讨论】:

  • 排序后你想要的matrix的布局是什么,为什么?

标签: c# list sorting


【解决方案1】:

豪尔赫。

一种可能的解决方案:

matrix.Sort(delegate(List<double> l1, List<double> l2)
            {
               return l1[0].CompareTo(l2[0]);
            });

再见。

【讨论】:

  • 太好了,这正是我需要的。
【解决方案2】:

您可以实现自己的 IComparer 并进行排序,或者您可以使用 Linq 做一些事情,这基本上会遍历整个矩阵并对其进行排序,或者您可以将其全部转换为另一个数据结构,例如 List> 然后您可以轻松排序。

或者是这样的:

How do I sort a two-dimensional array in C#?

http://www.codeproject.com/Tips/166236/Sorting-a-two-dimensional-array-in-C

【讨论】:

  • 杜祖,感谢您的回复。这些例子和我正在看,但不是我需要的。只有我必须对最外层进行排序。问候
【解决方案3】:

您可以按每个数组的第一个元素排序(如果这是您的要求):

var matrix = new double[][] {
    new[] { 100.0, -3.0, 50.0, 50.3 },
    new[] { 1.2, 1.1, 0.9, 10000.0 },
    new[] { 2.3, 2.35, 2.32, 2.299}
};

Array.Sort(matrix, (a, b) => a[0].CompareTo(b[0]));

【讨论】:

    猜你喜欢
    • 2018-09-10
    • 1970-01-01
    • 2014-05-30
    • 2011-07-09
    • 2020-07-09
    • 2014-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多