0

I have multiple columns in datatable like this:

   COL1   COL2 COL3      
   aaa    5    bla
   bbb    8    blablabla
   ccc    11   blabla
   ddd    9    bl
   eee    6    blabl

I'm trying to sort this datatable by COL1 asc and by COL2 desc BOTH!

I have tried the following solution but it doesn't exactly sort the second column:

DataTable dt = GetMyData();
dt.DefaultView.Sort = "COL1";
dt.DefaultView.Sort = "COL2 DESC";
dt = dt.DefaultView.ToTable();
tdog
  • 482
  • 3
  • 17

2 Answers2

1

Use LINQ to DataSet/DataTable

https://msdn.microsoft.com/en-us/library/bb386977.aspx

var newDt = dt.AsEnumerable()
            .OrderByDescending(x => x.Field<int>("COL2"))
            .ThenBy(x => x.Field<string>("COL1"))
            .CopyToDataTable();
Gerald Gonzales
  • 533
  • 2
  • 6
  • 20
1
  DataView sortedView = new DataView(dt);

  // Sort by COL1 and COL2
  sortedView.Sort = "COL1 DESC, COL2 ASC";

after this you should have sorted records in the data view

Sujit Singh
  • 799
  • 6
  • 11