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


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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250