Another way would be to use the dynamic query library. I've always wondered how difficult it would be to create an Expression dynamically. This would be a nice addition to my Audit Logger allowing for the configuration of an audit category to exist outside of the code.
Much of this code came from this stackoverflow.com article. I simply went and added the glue:
public static IEnumerable<T> Sort<T>(this IEnumerable<T> source,
string sortExpression, bool desc)
{
var param = Expression.Parameter(typeof(T), string.Empty);
var fields = sortExpression.Split('.');
Expression property = null;
Expression parentParam = param;
foreach (var field in fields)
{
property = Expression.Property(parentParam, field);
parentParam = property;
}
var sortLambda = Expression.Lambda<Func<T, object>>(
Expression.Convert(property, typeof(object)),
param);
if (desc)
{
return source.AsQueryable<T>().OrderByDescending<T, object>(sortLambda);
}
return source.AsQueryable<T>().OrderBy<T, object>(sortLambda);
}
Basically this will give you an expression which returns the value of a property. It will support property / field invocation so myObject.MyField.MyProperty. It works by creating an expression which represents the type of parameter being pased in to the lambda.
Then it builds an expression tree by chaining new expressions together for each token myObject, myField etc. Finally it creates a lambda which can be executed.
3 comments:
I was really confused in using the Dynamic Expression. This article has helped me a lot to complete. Thanks for sharing such nice article here.
I highly recommend LINQ in Action. It is enjoyable to read as well as a good reference for my development.thanks for this post and nice information.
r4 revolution per ds
Post a Comment