Articles → ADO.NET → Sort Data In Datatable In C#

Sort Data In Datatable In C#






Create A Datatable




Picture showing the sample data table with 3 columns and 4 rows
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


Picture showing the datatable after being sorted in an ascending order based on the salary
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Saturday, April 18, 2015

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250