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?

Answers


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.


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,

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.