Linq dynamic order by a list with example

Sort a list dynamically is easy, in this article we will create a class to sort the source dynamically by passing source, column and sort order.

Let’s write our class and then we will see it with example, create a new class DynamicSort

public static class DynamicSort
{
  public static IQueryable<T> OrderBy<T>(this IQueryable<T> source
      , string columnName, bool isAscending = true)
  {
     if (String.IsNullOrEmpty(columnName))
     {
       return source;
     }

     ParameterExpression parameter = Expression.Parameter(source.ElementType, "");

     MemberExpression property = Expression.Property(parameter, columnName);
     LambdaExpression lambda = Expression.Lambda(property, parameter);

     string methodName = isAscending ? "OrderBy" : "OrderByDescending";

     Expression methodCallExpression = Expression.Call(typeof(Queryable), methodName,
                           new Type[] { source.ElementType, property.Type },
                           source.Expression, Expression.Quote(lambda));

     return source.Provider.CreateQuery<T>(methodCallExpression);
  }
}

How we will create a simple aspx page to test our functionality, so here is the HTML of the page

<div>
  <asp:GridView ID="gvProduct" runat="server">    
  </asp:GridView>
</div>
<div>
  Column To Sort: <asp:TextBox ID="txtColumn" runat="server" />
</div>
<div>
  <asp:CheckBox ID="chkIsAscending" runat="server" Checked="true" text="Ascending?" />
</div>
<div>
   <asp:Button ID="btnSort" runat="server" Text="Sort" onclick="btnSort_Click" />
</div>

We will create a simple class product to create a list and pass it to sort

public class Product
{
    public Int32 Id { get; set; }
    public String Name { get; set; }
    public Int32 Qty { get; set; }
}

And here is the code for button click event:

protected void btnSort_Click(object sender, EventArgs e)
{
    List<Product> products = new List<Product>();
    products.Add(new Product { Id = 1, Name = "A", Qty = 10 });
    products.Add(new Product { Id = 2, Name = "C", Qty = 10 });
    products.Add(new Product { Id = 3, Name = "E", Qty = 10 });
    products.Add(new Product { Id = 4, Name = "D", Qty = 10 });
    products.Add(new Product { Id = 5, Name = "B", Qty = 10 });


    gvProduct.DataSource = DynamicSort.OrderBy(products.AsQueryable(), 
                              txtColumn.Text, chkIsAscending.Checked);
    gvProduct.DataBind();
}

Note: we converted our proudct to Queryable by using products.AsQueryable() before passing as parameter.

As you can see we added product with rough data to test our functionality and they are not in proper order because we have class to do this. Run your application and enter column name in text and define the order by selecting/unselecting the check box and click sort, that’s it.

Hamden Process manager with a reputed organization, Fond of learning new features and technology related to C#, ASP.Net, SQL Server, MVC etc.I like to help others, if I can
  • linq
  • c#
By Hamden On 07 Sep, 13  Viewed: 5,624

Other blogs you may like

Linq inner join, left outer join on two lists in C# with example

Joining two generic lists in linq is tricky, in this article we will see how we can join two lists by using inner join and then by using outer join. Using inner join is quite similar to sql inner join but outer join is a little different, so we will see it with example code as well as records... By Hamden   On 25 Sep 2013  Viewed: 39,590

Linq to Sql - Sort record on multiple columns in ascending or descending order

In SQL Server it's easy and we are familiar to sort orders on different columns but when it comes to Linq to SQL or Lamda expression we stuck how to sort the records, it is because we are experienced much. So let's discuss some daily use ordering of records with examples. **1**. Suppose we have... By Mike .Net   On 30 Jan 2013  Viewed: 4,915

Linq to SQL connection String to read from web.config file automatically

When we use Linq to SQL it creates a connection string in Settings files. When we need to create the DLL of the DataAccessLayer (DAL) for production server or any server which is not our current development server then we need to change connection string manually in Settings file, is not it would... By Montana Neyra   On 17 Jun 2012  Viewed: 5,080

How to use linq query on a datatable in C#

Is it possible to perform a linq query on datatable, answer is no because datatable’s row collection, DataRowCollection does not implement IEnumerable<T> so we cannot perform linq query on it. But if there is any way to convert our datatable data row collection into IEnumerable, then surely we can.... By Charles Fuller   On 25 Jun 2013  Viewed: 3,955

MVC paging with linq to sql and html helper class

To use paging in MVC you need to first create structure to pass values form page to HTML Helper class so first create a class to keep and pass the page information public class PagingInfo { public int TotalItems { get; set; } public int ItemsPerPage { get; set; } ... By Ali Adravi   On 03 Jan 2013  Viewed: 3,512