Search code examples
c#sortingdatatabledefaultview

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


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

Solution

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