我在datatable中有更多列(大约100列)。见下面的考试:
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;
我的问题是如何循环词典中的所有项目以在词典中添加更多 let 语句和 orderby 所有列。
请帮我修理一下。我的英语不好,抱歉
答案 0 :(得分: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();