您可以使用Linq OrderBy对Typed DataSet DataTables进行排序吗? [英] Can you sort Typed DataSet DataTables with Linq OrderBy?

查看:139
本文介绍了您可以使用Linq OrderBy对Typed DataSet DataTables进行排序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Typed DataSet DataTable,它继承了TypedTableBase<T>,而后者又实现了IEnumerable<T>.我似乎无法使它正常工作.

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

相反,我必须将此语句分配给IEnumerable(或列表),然后在提交之前用新订购的IEnumerable手动填充我的DataTable.这是预期的样子吗?我考虑过要创建自己的扩展方法,该方法将清空/重新填充我的数据表,但这是明智的吗?

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?

注意:通常,我只需要使用DataView进行排序即可查看.但是在这种情况下,我有一个自定义例程,该例程必须创建一个具有排序要求的新访问数据库,这意味着我需要对实际的DataTable进行排序,以便我可以重新提交它.

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.

谢谢.

推荐答案

为了执行您想要的操作,必须在项目中添加以下引用:

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

System.Data.DataSetExtensions

添加完后,您可以像这样订购DataTable:

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

为了遍历DataView,您可以执行以下操作:

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...
}

或者,您也可以通过LINQ以这种方式打字:

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...
}

这篇关于您可以使用Linq OrderBy对Typed DataSet DataTables进行排序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆