4

I have a Datatable contain n columns. I want to sort n columns in the datatable by LINQ but I don't know how to do that. I sorted successfully with 1 columns but I didn't with multi columns

Ex:

Dictionary<string, string> dict = Dictionary<string, string>
dict.Add("column_1", "asc");
dict.Add("column_2", "asc");
dict.Add("column_3", "asc");
...
dict.Add("column_n", "asc");
var Rows = from row in datatable.AsEnumerable()
           orderby n1 acsending  (I need loop to add all columns in Dictionary here to sort multi columns)
           select row 

How to loop n columns to add in orderby operator.

My problem is user have a array contain name of columns to sort and I need loop a array to add columns name in operator orderby to sort multi column

PS: My English is not good. Sorry

Thanks Nguyen

user1186850
  • 123
  • 1
  • 1
  • 7
  • possible duplicate of [Multiple "order by" in LINQ](http://stackoverflow.com/questions/298725/multiple-order-by-in-linq) – Andy Korneyev Jun 26 '15 at 15:44
  • I have commented detail about my problem. Please help me to resolve it – user1186850 Jun 26 '15 at 15:57
  • Possible duplicate of [How to sort DataTable by two columns in c#](http://stackoverflow.com/questions/16302901/how-to-sort-datatable-by-two-columns-in-c-sharp) – Sometowngeek Aug 05 '16 at 15:08

4 Answers4

2
list.OrderBy(x => x.att1).ThenByDescending(x => x.att2);

Could be ThenByAscending. Using a lambda in this situation would be cleaner to read as well.

Adam
  • 2,327
  • 16
  • 28
2

To use the dictionary as order definition you can use the following:

Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("col1", "asc");
dict.Add("col2", "desc");

DataTable datatable = new DataTable();
datatable.Columns.Add("col1");
datatable.Columns.Add("col2");
datatable.Rows.Add(new[] {"a", "1"});
datatable.Rows.Add(new[] {"b", "2"});
datatable.Rows.Add(new[] {"a", "5"});

datatable.DefaultView.Sort = 
                  String.Join(",", dict.Select(x => x.Key + " " + x.Value).ToArray());
datatable = datatable.DefaultView.ToTable();
1
datatable.AsEnumerable().OrderBy(c => c[0]).ThenBy(c => c[1]);

This will order the rows by the first and the second column

0

Try comma seperating the order by columns

var Rows = from row in datatable.AsEnumerable()
       orderby n1 acsending, n2
       select row 
Hugh
  • 440
  • 3
  • 13