Thursday, May 23, 2013

How to sort a data table in C# with LINQ

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();
            Console.WriteLine("Before sorting");
            var Rows = (from row in dataTable.AsEnumerable()
                        orderby row["FirstName"] descending
                        select row);
            dataTable = Rows.AsDataView().ToTable();
            Console.WriteLine("After sorting");

        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.


So it’s very easy. Hope you like it. Stay tuned for more updates…

Shout it


Your feedback is very important to me. Please provide your feedback via putting comments.

Search This Blog
About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews