views:

772

answers:

2

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

A: 

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

Kobi
Two questions related to this...1) When I do this I put "column1 asc,column2 asc" I expected the sort to be by column1 then column2 but it seems to be the other way. Is that expected? 2) Is there an easy way to deal with NULL in both column? (maybe that is just another StackOverflow question)
the empirical programmer
A: 
Partha Choudhury