Tuesday, May 5, 2009

Dynamic Expression

Scott Gu has a good article about a great sample component called Dynamic Linq. This is a very powerful addition to your linq toolkit which lets you create expressions based on strings. So imagine that you want to add sorting to a grid which is bound to a List. One way would be to have a switch statement for each options (Yes you can throw up I'll wait).

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:

stainless steel barometer said...

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.

John said...
This comment has been removed by the author.
John said...

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