Can you sort Typed DataSet DataTables with Linq OrderBy?

后端 未结 2 1568
梦毁少年i
梦毁少年i 2021-01-25 22:05

I have a Typed DataSet DataTable which inherits TypedTableBase, which in turn implements IEnumerable. I can\'t seem to get this to wo

2条回答
  •  醉梦人生
    2021-01-25 22:53

    In order to do what you want, you must add the following reference to your project:

    System.Data.DataSetExtensions

    Once you have that added, you can order your DataTable like this:

    var query = myDataTable.OrderBy(x => x.ID).ThenBy(y => y.ID2);
    
    // use the DataView generated from the LINQ query
    DataView dtv = query.AsDataView();  
    

    In order to iterate through the DataView, you can do the following:

    var dtv = query.AsDataView();
    foreach(DataRowView rw in dtv)
    {
        // you can also cast back to the typed data...
        MyCustomRowType typedRow = (MyCustomRowType) rw.Row;
    
        // do something here...
    }
    

    Alternatively you can typecast via LINQ this way:

    var dtv = query.AsDataView().Cast();
    
    // rowItem is of type MyCustomRowType...
    foreach(var rowItem in dtv)
    {
        // do something here...
    }
    

提交回复
热议问题