Sort Datatable using Linq C#.

Here I will show how to sort datatable using Linq C# queries.

using System;
using System.Data;
using System.Web.UI;

public partial class DataTable_Sorting : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs  e)
    {
        if (!Page.IsPostBack)
        {
            GetnSortDatatable(GenerateDatatable());
        }
    }

    private DataTable GenerateDatatable()
    {
        using (DataTable dtEmp = new DataTable())
        {
            dtEmp.Columns.Add(“Name”, typeof(string));
            dtEmp.Columns.Add(“Designation”, typeof(string));
            dtEmp.Columns.Add(“Salary”, typeof(decimal));
            dtEmp.Columns.Add(“Deduction”, typeof(decimal));

            string[] names = { “Sunil Kumar”, “Nisha”, “Amit Jha”, “Sunil Sharma”, “Garima singh”, “Karuna Pareek”, “Aakash”, “David”, “Maya”, “Sanjeev” };

            DataRow dr;
            for (int i = 1; i <= 10; ++i)
            {
                dr = dtEmp.NewRow();
                dr[“Name”] = names[i – 1];
                dr[“Designation”] = “Designation_” + i.ToString();
                dr[“Salary”] = (i * 1000);
                dr[“Deduction”] = (i * 100);
                dtEmp.Rows.Add(dr);
            }
            return dtEmp;
        }
    }

    private void GetnSortDatatable(DataTable dtEmp)
    {
        // Original Data
        grdOriginal.DataSource = dtEmp;
        grdOriginal.DataBind();

        // Datatable sorting
        grdSorted.DataSource = (from emp in dtEmp.AsEnumerable() orderby emp[“Name”] select emp).AsDataView().ToTable();
        grdSorted.DataBind();
    }
}

 

sort

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s