小编典典

如何在C#中对二维(矩形)数组排序?

c#

我有一个二维数组(字符串),它构成了我的数据表(行和列)。我想按任何列对该数组进行排序。我试图找到一种在C#中执行此操作的算法,但没有成功。

任何帮助表示赞赏。


阅读 562

收藏
2020-05-19

共1个答案

小编典典

将二维字符串数组加载到实际的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");

您也可以编写自己的方法来对二维数组进行排序。两种方法都是有用的学习经验,但是DataTable方法将使您开始学习在C#应用程序中处理数据表的更好方法。

2020-05-19