对DataTable集合的对象进行排序

时间:2012-06-20 15:36:11

标签: c# sorting

我使用

从数据库中获取所有表
tables = Utility.DBConnection.GetSchema("Tables", restrictions);

如何在以后按字母顺序排序表? 我检查了GetSchema,没有任何属性可以给出任何排序顺序。

我想稍后再做:

foreach (DataRow row in tables.Rows) {}

但我想在之前对表格进行排序。

4 个答案:

答案 0 :(得分:0)

只需从数据集中的集合中复制一个数组/表列表,然后自己排序吗?

答案 1 :(得分:0)

不确定Utility.DBConnection.GetSchema会返回什么,但这可能非常接近您想要的内容:

var sortedTables = from table in tables
                   orderby table.TableName ascending
                   select table;

答案 2 :(得分:0)

如果表是DataTable,您可以使用DataTable.DefaultView Property为数据提供排序视图:

DataView view = tables.DefaultView;

view.Sort = "Name";

foreach (DataRowView row in view)
{
}

答案 3 :(得分:0)

您可以使用排序字典-

DataTable dtTables = conn.GetSchema("Tables");
SortedDictionary<string, DataRow> dcSortedTables = new SortedDictionary<string, DataRow>();

foreach (DataRow table in dtTables.Rows) {
    string tableName = (string)table[2];
    dcSortedTables.Add(tableName, table);
}

// Loop through tables
foreach (DataRow table in dcSortedTables.Values) {
    // your stuff here
}