MVC LINQ dynamic orderBy getting column type

I am trying to dynamically order a list of products.

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?


Take a look at Dynamic LINQ, Scott Gu did a great post on it here

It makes it as easy as this

query = query.OrderBy(columnName);


//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.


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.

Need Your Help

Print special characters via php inside a html element's attribute

php html escaping

Assume $string = AX èdfdfdèsèdsè'/\" (actually, $string is assigned this value from the DB)

Search within the search results of an MYSQL Query

java mysql sql database search

I'm writing an app in java, that receives requests and save them to a file,