user6268526
user6268526

Reputation: 1

Expression Tree Confusion

I have lived in the pre ASP.NET 3.0 world for a long, long time. I have recently been exposed to all of the cool stuff that began in version 3.0. I think i have now got a pretty good grasp on Anonymous Functions and Delegates but this Expression Tree stuff is just blowing my mind. My first inclination is "why do I need to create such complicated code". Just looking at it makes me feel stupid and I have been writing code for over 25 years. Below is some code that I HOPE someone can clearly explain for me.

ParameterExpression param = Expression.Parameter(typeof (Product), "product");

Func<Product, object> func = Expression.Lambda<
    Func<Product, object>>(
    Expression.Convert(
        Expression.Property(param, typeof (Product).GetProperty(sidx)), typeof (object)
        ), param).Compile();


IEnumerable<Product> products = null;
switch (sord)
{
    case "asc":
        products = _productRepository.GetTop100Products().OrderBy(func)
            .Skip(pageIndex*pageSize).Take(pageSize).AsEnumerable();
        break;
    case "desc":
        products = _productRepository.GetTop100Products().OrderByDescending(func)
            .Skip(pageIndex*pageSize).Take(pageSize).AsEnumerable();
        break;
    default:
        break;
}

This is some code that queries products from the AdventureWorks database. Can some explain to me why all of this Expression.Lamba stuff is necessary? Is there another way to do whatever it is that is going on here?

Upvotes: 0

Views: 66

Answers (1)

svick
svick

Reputation: 245046

Doing this is only necessary if you need to select the property to sort by as a string. If you don't need that, you could hard-code the sort expression using a lambda:

Func<Product, object> func = product => product.sidx;

Or you could take that as a parameter of your function.

But if you actually want to sort using LINQ by a property that you're given as a string, then this is probably the best option. If you do similar things often, you can of course hide all this behind a helper method, which could simplify the code significantly.


Also, if you're trying to use LINQ to SQL or something similar, then your code is wrong. Func<Product, object> can't be translated into SQL, only Expression<Func<Product, object>> can. What this means is that you should remove the call to Compile() from your code.

Upvotes: 2

Related Questions