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
?
答案 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)
如果您使用的是DataTableExtensions
和DataRowExtensions
:
var view = dt.AsEnumerable().OrderBy(c=>c.Field<int>("id")).AsDataView();