Ger*_*ton 1 c# linq sorting datatable
我有一个ADO.Net数据表,我需要首先按column1然后按column2排序,其中任何一个都可能有空值.排序后,我需要从行中读取一些值并添加到列表视图中.
我编写了代码来执行此DataTable.DefaultView.Sort(运行两次).但想知道是否有更好的方法.
我在想LINQ ......所以我试过了:
OrderedEnumerableRowCollection<DataRow> queryX = dt.AsEnumerable()
.OrderBy(c => c.Field<int?>("column1"))
.ThenBy(c => c.Field<int?>("column2"));
Run Code Online (Sandbox Code Playgroud)
但这个错误随之而来"System.InvalidCastException was unhandled".我假设这是由NULL引起的,所以就像我在数据表上指定查询的测试一样"where column1 IS NOT NULL",错误仍然发生.
我的LINQ经验并不多,所以我的问题是:
TEP
Kob*_*obi 10
如果您有DataTable,请查看DataView:
private void SortByTwoColumns()
{
// Get the DefaultViewManager of a DataTable.
DataView view = DataTable1.DefaultView;
// By default, the first column sorted ascending.
view.Sort = "State, ZipCode DESC";
}
Run Code Online (Sandbox Code Playgroud)
来源:http: //msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx