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:
- What is incorrect with my code above? Conceptually I'm I missing something on how LINQ works?
- Why does filtering out the Nulls still cause this? Again, conceptually I'm I missing something on how LINQ works
- Is there a better\correct LINQ query that would to this?
- Is there a better\correct (more elegant) way to do this (using LINQ or not)?
tep