user1263390
user1263390

Reputation: 187

sort datatable by a field

  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);
    }

How can I sort DataTable by id?

Upvotes: 3

Views: 2475

Answers (4)

code4life
code4life

Reputation: 15794

If you're using DataTableExtensions and DataRowExtensions:

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

Upvotes: 0

Duane Theriot
Duane Theriot

Reputation: 2185

Why not sort in your original query?

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);
}

Upvotes: 1

Christian Hayter
Christian Hayter

Reputation: 31071

DataTables cannot be sorted directly, but you can create a DataView of the table with a specific sort order.

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

Upvotes: 4

ionden
ionden

Reputation: 12776

Try using this:

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

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

Upvotes: 5

Related Questions