Can you sort Typed DataSet DataTables with Linq OrderBy?

人走茶凉 提交于 2019-12-02 18:31:00

问题


I have a Typed DataSet DataTable which inherits TypedTableBase<T>, which in turn implements IEnumerable<T>. I can't seem to get this to work.

myDataTable.OrderBy(x => x.ID).ThenBy(y => y.ID2);

Instead I have to assign this statement to an IEnumerable(or List), then refill my DataTable manually with the newly ordered IEnumerable before I commit. Is this how it is intended to be? I've thought about creating my own extension method that will empty/refill my DataTables, but would this be wise?

Note: Typically I only need to sort for viewing purposes using DataView. But in this case I have a custom routine that must create a new access database with sorting requirements, which means I need to sort the actual DataTable so that I may re-commit it.

Thank you.


回答1:


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<MyCustomRowType>();

// rowItem is of type MyCustomRowType...
foreach(var rowItem in dtv)
{
    // do something here...
}



回答2:


Linq extension methods do not alter the source enumerable.

var numbers = new int[]{1,2,3};
var reversed = numbers.OrderByDescending(x=>x);
foreach(var number in reversed)
  Console.Write(number); // 321
foreach(var number in numbers)
  Console.Write(number); // 123

If you want to sort a DataTable, you should be using DataViews. You create a view on your DataTable, then apply a Sort or Filter to it, then bind against it. Keep in mind DataSets are an older technology and not quite up to date on the latest and the greatest. A "newer" approach would be to use the Entity Framework.



来源:https://stackoverflow.com/questions/3916689/can-you-sort-typed-dataset-datatables-with-linq-orderby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!