Articles → ADO.NET → Sort Data In Datatable In C#
Sort Data In Datatable In C#
Create A Datatable
Click to Enlarge
DataTable table = new DataTable();
// Adding columns
table.Columns.Add(new DataColumn("Name",Type.GetType("System.String")));
table.Columns.Add(new DataColumn("Age", Type.GetType("System.Int32")));
table.Columns.Add(new DataColumn("Salary", Type.GetType("System.Int32")));
// Adding Rows
DataRow row = table.NewRow();
row["Name"] = "Name1";
row["Age"] = 30;
row["Salary"] = 50000;
table.Rows.Add(row);
row = table.NewRow();
row["Name"] = "Name2";
row["Age"] = 25;
row["Salary"] = 25000;
table.Rows.Add(row);
row = table.NewRow();
row["Name"] = "Name3";
row["Age"] = 35;
row["Salary"] = 70000;
table.Rows.Add(row);
row = table.NewRow();
row["Name"] = "Name4";
row["Age"] = 25;
row["Salary"] = 15000;
table.Rows.Add(row);
Sort
DataTable sortedTable = table.AsEnumerable().OrderBy(r => r.Field < int > ("Age"))
.ThenBy(r => r.Field < int > ("Salary")).CopyToDataTable();
Output
Click to Enlarge