How to sort a data table in C# with LINQ

added by jalpesh
5/22/2013 6:48:41 PM


One of friend today ask how we can sort data table based on particular column? So I thought it’s a good idea to write a blog post about it. In this blog post we learn how we can learn how we can sort database with LINQ queries without writing much more long code. So let’s write a code for that. using System; using System.Data; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { DataTable dataTable = CreateDataTalble(); AddRowToDataTable(dataTable); Console.WriteLine("Before sorting"); PrintDatable(dataTable); var Rows = (from row in dataTable.AsEnumerable() orderby row["FirstName"] descending select row); dataTable = Rows.AsDataView().ToTable(); Console.WriteLine("=============================="); Console.WriteLine("After sorting"); PrintDatable(dataTable); } public static DataTable CreateDataTalble() { DataTable dt = new DataTable(); dt.Columns.Add("FirstName", typeof(string)); dt.Columns.Add("LastName", typeof(string)); return dt; } public static void AddRowToDataTable(DataTable dt) { dt.Rows.Add("Jalpesh", "Vadgama"); dt.Rows.Add("Vishal", "Vadgama"); dt.Rows.Add("Teerth", "Vadgama"); dt.Rows.Add("Pravin", "Vadgama"); } public static void PrintDatable(DataTable dt) { foreach (DataRow row in dt.Rows) { Console.WriteLine(string.Format("{0} {1}", row[0], row[1])); } } } }