Reputation: 42660
I have an ADO.Net datatable
that I need to sort by first by column1 then by column2, either of which may have nulls. Once sorted I need to read some values out of the rows and add to a listview.
I have written code to do this DataTable.DefaultView.Sort (run twice). But wondering if there might be a better way.
I was thinking maybe LINQ...so I tried :
OrderedEnumerableRowCollection<DataRow> queryX = dt.AsEnumerable()
.OrderBy(c => c.Field<int?>("column1"))
.ThenBy(c => c.Field<int?>("column2"));
But this errors with "System.InvalidCastException was unhandled"
. I assumed this is caused by the NULLs so just as a test I specifying a query on the datatable "where column1 IS NOT NULL"
and the error still happens.
I don't really have much LINQ experience so my questions are:
tep
Upvotes: 1
Views: 12451
Reputation: 534
Not sure what the datatypes are for those columns, I'm assuming they are int but if your database is Oracle, try the following:
OrderedEnumerableRowCollection<DataRow> queryX = dt.AsEnumerable()
.OrderBy(c => c.Field<decimal?>("column1"))
.ThenBy(c => c.Field<decimal?>("column2"));
Upvotes: 0
Reputation: 138127
If you have a DataTable, take a look at 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";
}
Source: http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx
Upvotes: 11