views:

592

answers:

2

Let's assume that I have two classes:

class person
{
    int ID
    string name
    Address address
}
class address
{
    int ID
    string street
    string country
}

These classes are more or less given, they are mapped via nHibernate to be honest :)

In a grid (datatables.net as base) I would like to have a type-independent sorting.

Therefore I created a lambda expression:

  var param = Expression.Parameter(typeof(T), typeof(T).Name);
  var sortExpression = Expression.Lambda<Func<T, object>>
                              (Expression.Convert(Expression.Property(param, "Property to sort"), typeof(object)), param);

If I pass Person as Type T and replace the "Property to sort" with "name" it works fine (creates a correct lambda). If the Property to sort is "address.street" it won't work, throw me the following error:

Property 'address.street' is not defined for type 'person'

I see only one solution so far, but not clear enough... I would try to split the string which contains the Property-Name (split by .)

Can anyone give a better solution? I need to add the sortExpression to an IQueryable object query.OrderBy(sortExpression).

Not sure if my title is clear, please go ahead and correct it.

Thanks in advance.

A: 

It seems to me you're trying to rewrite Microsoft DynamicQuery. Why not just use that instead?

Here's an example:

IQueryable<Foo> myQuery = GetHibernateQuery();
myQuery = myQuery.OrderBy("address.street");
Craig Stuntz
Because I only get an IQueryable object which contains a bunch of data already, then I add the paging and so on, afterwards I load only the data left in the query. This is done by nHibernate. Only for the sorting it cannot be the solution (I hope)
griti
That's my point. DynamicQuery can already do this "add the sorting to an existing queryable." I have a demo solution on my blog which does just this. http://blogs.teamb.com/craigstuntz/2009/04/27/38243/
Craig Stuntz
oh thanks, will read trough it
griti
I added a trivial example to the post.
Craig Stuntz
A: 

What is not clear?

You have to split it and then use:

Expression.Property(Expression.Property(param, "address"), "street")
LukLed
uhm and how would you do that if maybe there comes something like`person.company.address.street` ? I just don't know how to "nest" it.. or if there are some other ways, like Craig posted...
griti
Expression.Property(Expression.Property(Expression.Property(Expression.Property(param, "person"), "company"),"address"),"street")Simple loop will work.
LukLed
not by hand? :)
griti