Intro
Let's say that I have these classes:
public class Door {
public string Label { get; set; }
}
public class House {
public string Address { get; set; }
public Door FrontDoor { get; set; }
}
Now, those are simple models in the DB, abstracted using Entity Framework 4. Therefore, when I need to make an ordered list of House
then I can use:
dbObjectContext.Houses.OrderBy(h=>h.Name);
Then, if I want to order by FrontDoor.Label
, I can use:
dbObjectContext.Houses.OrderBy(h=>h.FrontDoor.Label);
Problem
I intend to make a sorting method that is intended to be used by a WPF DataGrid that will display a list of Houses. The method signature is like below:
IOrderedQueryable<TEntity> ApplySortingToQuery<TEntity>(bool ascending
,IQueryable<TEntity> finderQuery,string propertyPath)
I want to build OrderBy expression using the knowledge of the object type TEntity
and the property access path string propertyPath
.
In the DataGrid, the objects to be sorted is of type House
, and it's columns are Address and Front Door Label. Now, the Address column in the DataGrid has SortMemberPath
set to Address
. Whereas, the Front Door Label column's is FrontDoor.Label
.
In the beginning, I can just use if-else
to determine what the OrderBy expression to be used, e.g.:
if (col.SortMemberPath=="Address") {
query=query.OrderBy(h=>h.Address);
} else if (col.SortMemberPath=="FrontDoor.Label") {
query=query.OrderBy(h=>h.FrontDoor.Label);
}
However, this functionality is very generic IMHO. So, a utility function to do it that will consult SortMemberPath
and use it as propertyPath
in the method is going be a great help for many other applications that will use it.
I've consulted this technique that help me to somewhat make this utility function, but only direct property access is successful (i.e.: Address
), but accessing sub property (i.e.: FrontDoor.Label
) isn't successful.
Please guide me.