Sorting datatable by two columns with one column asc and the other one desc c#

2k Views Asked by At

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();
2

There are 2 best solutions below

0
Gerald Gonzales On BEST ANSWER

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();
0
Sujit Singh On
  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