我有一个 ADO.Net datatable
我需要先按 column1 然后按 column2 排序,其中任何一个都可能有空值。排序后,我需要从行中读取一些值并添加到 ListView 中。
我已经编写了代码来执行此 DataTable.DefaultView.Sort(运行两次)。但想知道是否有更好的方法。
我在想也许是LINQ ...所以我尝试了:
OrderedEnumerableRowCollection<DataRow> queryX = dt.AsEnumerable()
.OrderBy(c => c.Field<int?>("column1"))
.ThenBy(c => c.Field<int?>("column2"));
但是这个错误 "System.InvalidCastException was unhandled"
.我假设这是由 NULL 引起的,所以就像我在数据表 "where column1 IS NOT NULL"
上指定查询一样作为测试。并且错误仍然发生。我真的没有太多 LINQ 经验,所以我的问题是:
泰普
最佳答案
如果您有 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";
}
来源:
http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx
关于c# - 如何按 2 列对 DataTable 进行排序,使用 NULL,也许使用 LINQ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1651263/