Search code examples
c#asp.net-mvclinqdynamic-typing

MVC LINQ dynamic orderBy getting column type


I am trying to dynamically order a list of products.

Product:
price (int)
name (string)

So far I have managed to get the following:

string columnToOrderBy = "price";
ParameterExpression param = Expression.Parameter(typeof(Product), "p");
var ordering = Expression.Lambda<Func<Product, double>>(Expression.Property(param, columnToOrderBy), param);

this works for ordering by price, however it won't work when ordering by name because of the column type.

Expression.Lambda<Func<Product, double>>

Is there anyway to get the type of a column to set it in the Func method?


Solution

  • Take a look at Dynamic LINQ, Scott Gu did a great post on it here http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

    It makes it as easy as this

    query = query.OrderBy(columnName);
    

    or

    //orderby descending
    query = query.OrderBy(columnName + " DESC");
    

    There's no need to mess around with manually manipulating expression trees when you don't have to. Using dynamic LINQ will make your code easier to understand and maintain.


    Edit

    You can now install this as a Nuget package, but none of them seem to be from an official source (at the time of writing).

    Here's a vanilla package containing the code that Scott Gu presented.

    Here's a branch of Scott's code that has been expanded to include more features. It appears to be under active development, and looks quite interesting.