0

I have the following values in my dataview dv :

  1,2,0,4,2,1,0,0

I would like to sort it in ascending order while keeping the 0 values to the last, something like this :

  1,1,2,2,4,0,0,0

I am currently doing this :

   DataSet ds = (DataSet)Session["test"];
   DataTable dt = ds.Tables[0];
   DataView dv = new DataView(dt);
   dv.Sort = "Value";

This gives me the following output :

 0,0,0,1,1,2,2,4

Is there a way I can get the 0 values to the last ?

I have also tried using the dv.RowFilter but that excludes the 0's completely. I would like to include the 0's. Is there a way I can do this ?

CodeNinja
  • 3,188
  • 19
  • 69
  • 112
  • [This](http://stackoverflow.com/questions/582374/dataview-sort-more-than-just-asc-desc-need-custom-sort) might be usefull for you – Drasive Jun 10 '13 at 14:59
  • Thanks Drasive ! I dont think I can accomplish what I am looking to do here. – CodeNinja Jun 11 '13 at 12:58

1 Answers1

0

You could use Linq-To-DataSet which is also more powerful, less error-prone and more readable.

DataTable orderedTable = ds.Tables[0].AsEnumerable()
    .OrderBy(row => row.Field<int>("Value") == 0)
    .ThenBy(row => row.Field<int>("Value"))
    .CopyToDataTable();

This works because row.Field<int>("Value") == 0 returns a bool if the value is 0. Enumerable.OrderBy orders ascending(as opposed to OrderByDescending), since true can be understood as 1 and false as 0 all Value=0 are coming last.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939