如何在C#中对二维(矩形)数组排序? [英] How do I sort a two-dimensional (rectangular) array in C#?

查看:196
本文介绍了如何在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.

感谢您的帮助.

推荐答案

将二维字符串数组加载到实际的DataTable(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆