Jac*_*ack 34 c# arrays sorting
我有一个二维数组(字符串)组成我的数据表(行和列).我想按任何列对此数组进行排序.我试图在C#中找到一个算法,但是没有成功.
任何帮助表示赞赏.
Mar*_*ell 41
我可以检查 - 你的意思是矩形数组([,])或锯齿状数组([][])?
对锯齿状阵列进行排序非常容易; 我在这里讨论一下.显然,在这种情况下,Comparison<T>将涉及一个列而不是按顺序排序 - 但非常相似.
对矩形数组进行排序比较棘手......我可能很想将数据复制到矩形数组或a中List<T[]>,然后在那里排序,然后复制回来.
这是一个使用锯齿状数组的例子:
static void Main()
{ // could just as easily be string...
int[][] data = new int[][] {
new int[] {1,2,3},
new int[] {2,3,4},
new int[] {2,4,1}
};
Sort<int>(data, 2);
}
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]));
}
Run Code Online (Sandbox Code Playgroud)
对于使用矩形数组......好吧,这里有一些代码可以在两者之间交换......
static T[][] ToJagged<T>(this T[,] array) {
int height = array.GetLength(0), width = array.GetLength(1);
T[][] jagged = new T[height][];
for (int i = 0; i < height; i++)
{
T[] row = new T[width];
for (int j = 0; j < width; j++)
{
row[j] = array[i, j];
}
jagged[i] = row;
}
return jagged;
}
static T[,] ToRectangular<T>(this T[][] array)
{
int height = array.Length, width = array[0].Length;
T[,] rect = new T[height, width];
for (int i = 0; i < height; i++)
{
T[] row = array[i];
for (int j = 0; j < width; j++)
{
rect[i, j] = row[j];
}
}
return rect;
}
// fill an existing rectangular array from a jagged array
static void WriteRows<T>(this T[,] array, params T[][] rows)
{
for (int i = 0; i < rows.Length; i++)
{
T[] row = rows[i];
for (int j = 0; j < row.Length; j++)
{
array[i, j] = row[j];
}
}
}
Run Code Online (Sandbox Code Playgroud)
Mus*_*sis 25
将二维字符串数组加载到实际的DataTable(System.Data.DataTable)中,然后使用DataTable对象的Select()方法生成DataRow对象的排序数组(或使用DataView获得类似的效果).
// assumes stringdata[row, col] is your 2D string array
DataTable dt = new DataTable();
// assumes first row contains column names:
for (int col = 0; col < stringdata.GetLength(1); col++)
{
dt.Columns.Add(stringdata[0, col]);
}
// load data from string array to data table:
for (rowindex = 1; rowindex < stringdata.GetLength(0); rowindex++)
{
DataRow row = dt.NewRow();
for (int col = 0; col < stringdata.GetLength(1); col++)
{
row[col] = stringdata[rowindex, col];
}
dt.Rows.Add(row);
}
// sort by third column:
DataRow[] sortedrows = dt.Select("", "3");
// sort by column name, descending:
sortedrows = dt.Select("", "COLUMN3 DESC");
Run Code Online (Sandbox Code Playgroud)
您也可以编写自己的方法来对二维数组进行排序.这两种方法都是有用的学习经验,但DataTable方法可以让您开始学习在C#应用程序中处理数据表的更好方法.
| 归档时间: |
|
| 查看次数: |
94511 次 |
| 最近记录: |