【问题标题】:Sorting the objects of a DataTable collection对 DataTable 集合的对象进行排序
【发布时间】:2018-12-11 05:28:39
【问题描述】:

我使用

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

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

我想稍后再做:

foreach (DataRow row in tables.Rows) {}

但我想先对表格进行排序。

【问题讨论】:

标签: c# sorting


【解决方案1】:

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

DataView view = tables.DefaultView;

view.Sort = "Name";

foreach (DataRowView row in view)
{
}

【讨论】:

  • 在我得到它如何使用它之后就开始工作了。谢谢。
  • 如果您通过应用程序层传递通用接口,这将无济于事。 (例如,如果您有一个方法期望 DataSet 被传入,并且由于某种原因您需要更改排序顺序)
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      您可以使用排序字典 --

      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
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-27
        • 1970-01-01
        相关资源
        最近更新 更多