2012-03-22 71 views
3
var course = from b in DbModle.courses 
          where b.name == "test" 
          select b; 

    DataTable dt = new DataTable(); 
    DataRow dr; 
    dt.Columns.Add(new DataColumn("name", typeof(string))); 
    dt.Columns.Add(new DataColumn("id", typeof(int))); 
    foreach (var course1 in course_university) 
    { 
     dr = dt.NewRow(); 
     dr[0] = course1.name; 
     dr[1] = course1.id; 
     dt.Rows.Add(dr); 
    } 

如何按ID排序DataTable按字段排序數據表

回答

4

數據表不能直接排序,但您可以創建表格的數據視圖與特定的排序順序。

var view = new DataView(dt) { Sort = "id" }; 
4

嘗試使用這樣的:

dt.DefaultView.Sort = "id"; 
DataView dv = dt.DefaultView; 

foreach (var row in dv) { 
    //. . . 
} 
1

爲什麼不在你原來的查詢中排序?

var courses = from c in DbModel.courses 
       where c.Name == "test" 
       orderby c.ID 
       select c; 

var dt = new DataTable(); 
dt.Columns.Add(new DataColumn("name", typeof(string))); 
dt.Columns.Add(new DataColumn("id", typeof(int))); 

foreach (var course in courses) 
{ 
    var dr = dt.NewRow(); 
    dr[0] = course1.name; 
    dr[1] = course1.id; 
    dt.Rows.Add(dr); 
} 
+0

怎麼可以這樣寫一個例子 – user1263390 2012-03-22 21:29:53

+0

退房在LINQ查詢的OrderBy行。 – 2012-03-22 21:32:17

0

如果您使用DataTableExtensionsDataRowExtensions

var view = dt.AsEnumerable().OrderBy(c=>c.Field<int>("id")).AsDataView();