Sorting a Data Table

后端 未结 5 1858
借酒劲吻你
借酒劲吻你 2020-12-01 17:47

I tried to sort a data table with following two ways

table.DefaultView.Sort = \"Town ASC, Cutomer ASC\"

table.Select(\"\", \"Town ASC, Cutomer ASC\")


        
相关标签:
5条回答
  • 2020-12-01 18:18

    Try this:

    Dim dataView As New DataView(table)
    dataView.Sort = " AutoID DESC, Name DESC"
    Dim dataTable AS DataTable = dataView.ToTable()
    
    0 讨论(0)
  • 2020-12-01 18:18

    This worked for me:

    dt.DefaultView.Sort = "Town ASC, Cutomer ASC";
    dt = dt.DefaultView.ToTable();
    
    0 讨论(0)
  • 2020-12-01 18:22
    private void SortDataTable(DataTable dt, string sort)
    {
    DataTable newDT = dt.Clone();
    int rowCount = dt.Rows.Count;
    
    DataRow[] foundRows = dt.Select(null, sort);
    // Sort with Column name
    for (int i = 0; i < rowCount; i++)
    {
    object[] arr = new object[dt.Columns.Count];
    for (int j = 0; j < dt.Columns.Count; j++)
    {
    arr[j] = foundRows[i][j];
    }
    DataRow data_row = newDT.NewRow();
    data_row.ItemArray = arr;
    newDT.Rows.Add(data_row);
    }
    
    //clear the incoming dt
    dt.Rows.Clear();
    
    for (int i = 0; i < newDT.Rows.Count; i++)
    {
    object[] arr = new object[dt.Columns.Count];
    for (int j = 0; j < dt.Columns.Count; j++)
    {
    arr[j] = newDT.Rows[i][j];
    }
    
    DataRow data_row = dt.NewRow();
    data_row.ItemArray = arr;
    dt.Rows.Add(data_row);
    }
    }
    
    0 讨论(0)
  • 2020-12-01 18:33

    This was the shortest way I could find to sort a DataTable without having to create any new variables.

    DataTable.DefaultView.Sort = "ColumnName ASC"
    DataTable = DataTable.DefaultView.ToTable
    

    Where:

    ASC - Ascending

    DESC - Descending

    ColumnName - The column you want to sort by

    DataTable - The table you want to sort

    0 讨论(0)
  • 2020-12-01 18:37

    After setting the sort expression on the DefaultView (table.DefaultView.Sort = "Town ASC, Cutomer ASC" ) you should loop over the table using the DefaultView not the DataTable instance itself

    foreach(DataRowView r in table.DefaultView)
    {
        //... here you get the rows in sorted order
        Console.WriteLine(r["Town"].ToString());
    }
    

    Using the Select method of the DataTable instead, produces an array of DataRow. This array is sorted as from your request, not the DataTable

    DataRow[] rowList = table.Select("", "Town ASC, Cutomer ASC");
    foreach(DataRow r in rowList)
    {
        Console.WriteLine(r["Town"].ToString());
    }
    
    0 讨论(0)
提交回复
热议问题