[英]Sorting two dimensional array by columns in C#
I want to sort two-dimensional array.我想对二维数组进行排序。 Instead of ordering for the first dimension I want to order the inner dimension.
我不想订购第一个维度,而是订购内部维度。
For example if initial array is like this:例如,如果初始数组是这样的:
{{4, 1, 3},
{6, 5, 2},
{0, 9, 8}}
Then if we sort array by first row, result will be:然后,如果我们按第一行对数组进行排序,结果将是:
{{1, 3, 4},
{5, 2, 6},
{9, 8, 0}}
I managed doing this by transposing the array, ordering and transposing again.我通过转置数组,再次排序和转置来做到这一点。 But is there a better way to do it?
但是有没有更好的方法呢?
If you can allow to use Linq
, the easiest way is the following:如果您可以允许使用
Linq
,最简单的方法如下:
First add namespace using System.Linq;
首先
using System.Linq;
Sorting: Array.ForEach(myArray, row => Array.Sort(row));
排序:
Array.ForEach(myArray, row => Array.Sort(row));
This will iterate over rows and sort by ascending.这将遍历行并按升序排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.