我如何排序在C#中的二维数组? [英] How do I sort a two-dimensional array in C#?
问题描述
我有一个二维数组(串),这使我的数据表(行和列)。我想排序这个数组按任何列。我试图找到在C#这样的算法,但都没有成功。
I have a two-dimensional array (of Strings) which make up my data table (of rows and columns). I want to sort this array by any column. I tried to find an algorithm for doing this in C#, but have not been successful.
任何帮助是AP preciated。
Any help is appreciated.
推荐答案
装入二维字符串数组到一个实际的数据表(System.Data.DataTable),然后使用DataTable对象的Select()方法来生成一个分类DataRow对象的数组(或使用类似的效果一个DataView)。
Load your two-dimensional string array into an actual DataTable (System.Data.DataTable), and then use the DataTable object's Select() method to generate a sorted array of DataRow objects (or use a DataView for a similar effect).
// 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");
您也可以编写自己的方法来进行排序二维数组。这两种方法都将是有益的学习经验,但DataTable的做法将让你开始学习处理在C#应用程序的数据表的更好的方法。
You could also write your own method to sort a two-dimensional array. Both approaches would be useful learning experiences, but the DataTable approach would get you started on learning a better way of handling tables of data in a C# application.
这篇关于我如何排序在C#中的二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!