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])); } } } }
So here in the above application , First I have created a datable with two column ‘FirstName’ and ‘LastName’ in CreateDataTable function. Also I have create a function called ‘AddRowToDataTable’
to add some rows. Then I have created a common function to print a datable with Console.Writeline.
Now to short the datable I have used a LINQ feature to convert database as IEnumerable and then I have used ‘OrderBy’ operator to sort IEnumerable with First Name row. It will return a sorted EnumerableRowCollection of rows.
Then I have converted EnumerableRowCollection to dataview and then cast as datable. That’s it. We are done with code. Let’s run this example and see how its works.
![SortDataTableWithLinqCsharp SortDataTableWithLinqCsharp](https://lh4.ggpht.com/-ONSgCnUwfmg/UZ0RtEBuftI/AAAAAAAACe0/MVXS9pMyPMA/SortDataTableWithLinqCsharp_thumb%25255B1%25255D.png?imgmax=800)
So it’s very easy. Hope you like it. Stay tuned for more updates…
Good one Jalpesh
ReplyDeleteAny perfomance related issue using this ?
Kirti its faster then for loop!!
ReplyDeletethank for good code stuff
ReplyDeleteit help me lot
Thanks
Delete