如何在 C# 中按行对锯齿状数组进行排序? [英] How do I sort jagged array by row in C#?
本文介绍了如何在 C# 中按行对锯齿状数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有二维锯齿状数组.我想按任何行对其进行排序.
I have 2D jagged array. And I want to sort it by any rows.
我搜索并找到了按列排序的代码
I've searched and found code for sorting by columns
private static void Sort<T>(T[][] data, int col)
{
Comparer<T> comparer = Comparer<T>.Default;
Array.Sort<T[]>(data, (x,y) => comparer.Compare(x[col],y[col]));
}
我可以调整它以按任何行排序吗?
Can I adapt it for sort by any rows ?
感谢任何帮助.
我的锯齿状数组示例(已添加)
Sample of my jagged array (Added)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
int n = 10;
int[][] capm = new int[3][];
for (int i = 0; i <= 2; i++)
{
capm[i] = new int[n + 1];
}
Random rand = new Random();
for (int i = 1; i <= n; i++)
{
capm[1][i] = i;
}
for (int i = 1; i <= n; i++)
{
capm[2][i] = rand.Next(1, 6);
}
Sort(capm, 2);
Console.ReadLine();
}
private static void Sort<T>(T[][] data, int col)
{
data = data.OrderBy(i => i[col]).ToArray();
}
}
}
@Dani &@Martin 我希望我的锯齿状数组按 capm[2][] 排序.
@Dani & @Martin I want my jagged array to sort by capm[2][].
推荐答案
我能想到的唯一方法是按索引数组排序:
The only way I can think of doing this is sorting by an array of indices:
private static void Sort<T>(T[][] data, int row)
{
int[] Indices = new int[data[0].Length];
for(int i = 0; i < Indices.Length; i++)
Indices[i] = i;
Comparer<T> comparer = Comparer<T>.Default;
Array.Sort(Indices, (x, y) => comparer.Compare(data[row][x], data[row][y]);
for(int i = 0; i < data.Length; i++)
{
T[] OldRow = (T[])data[i].Clone();
for(int j = 0; j < OldRow.Length; j++)
data[i][j] = OldRow[i][Indices[j]];
}
}
这篇关于如何在 C# 中按行对锯齿状数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文