1

I have more columns in datatable (about 100 columns). See examble below:

 Column 1 | Column 2 | Column 3 | ..... | Column n 
 1;Nick   | 1        | USA      | ..... | Value 1
 2;David  | 2        | Reston   | ..... | Value 2
 3;Marry  | 3        | Spain    | ..... | Value 3
 4;Join   | 4        | Italy 3  | .....  Value 4
Dictionary<string, string > dict = new Dictionary<string, string>();
dict.Add("Column_1", "asc");
dict.Add("Column_2", "asc");
dict.Add("Column_1", "desc");
...................
dict.Add("Column_n", "asc");

var myRows = from row in datatable.AsEnumerable()
             let myID = int.Parse(row.Field<string>("Column 2"))
             let name = row.Field<string>("Column 1").Split(';')[1]
             ....
             orderby myID ascending, name descending, ......, column n asc
             select row;

My problem is how to loop all items in Dictionary to add more let statements and orderby all columns in Dictionary.

Please help me to fix it. My english is not good, sorry

1 Answers1

1
Dictionary<string, string > dict = new Dictionary<string, string>();
dict.Add("col1", "ASC");
dict.Add("col2", "ASC");
dict.Add("col3", "DESC");
DataTable dt = new DataTable();
dt.Columns.Add("col1");
dt.Columns.Add("col2");
dt.Columns.Add("col3");
Random r = new Random();
for (int i = 0; i < 20; i++)
    dt.Rows.Add(r.Next(10), r.Next(4), r.Next(2));
string sort = "";
foreach (KeyValuePair<string, string> entry in dict)
    sort = sort + " " + entry.Key + " " + entry.Value + ",";
sort = sort.Substring(0, sort.Length - 1).Trim();
dt.DefaultView.Sort = sort;
dt = dt.DefaultView.ToTable();
Nam Bình
  • 412
  • 2
  • 13
  • Nice. I'd use a string builder, but other than that, great :) – Noctis Jun 27 '15 at 09:03
  • Could i use linq to do that. I don't want to use dataview. Because i have to custom value before sorting. Ex: I need to split(';') value column 1 – Ngô Thành Nguyên Jun 27 '15 at 13:54
  • What you need is [Dynamic LINQ Library](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx). Ps: you can prepare data before passing it to datatable too :) – Nam Bình Jun 29 '15 at 07:46