按字段排序数据

时间:2012-03-22 21:17:17

标签: c# sorting datatable

  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 个答案:

答案 0 :(得分:5)

尝试使用:

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

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

答案 1 :(得分:4)

无法直接对DataTable进行排序,但您可以使用特定的排序顺序创建表的DataView。

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

答案 2 :(得分: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);
}

答案 3 :(得分:0)

如果您使用的是DataTableExtensionsDataRowExtensions

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