Practical use of expression trees

Expression trees are a good feature, but what are their practical applications? Can they be used for code generation or metaprogramming, or for some of them?

+62
c # expression-trees
Dec 31 '09 at 14:36
source share
8 answers

As John notes, I use them to provide common operators with .NET 3.5. I also use them (again in MiscUtil) to provide quick access to non-default constructors (you cannot use Delegate.CreateDelegate with constructors, but Expression works fine).

Other uses of manually created expression trees:

But indeed, expression is a very universal way of writing any dynamic code. Much easier than Reflection.Emit , and for my money it’s easier to understand than CodeDOM. And in .NET 4.0 you have even more options . I show the basics of writing code through Expression on my blog .

+40
Dec 31 '09 at 15:32
source share
β€” -
Mark Gravell used them in the MiscUtil effect to implement common operators .
+20
Dec 31 '09 at 14:48
source share

I just created a generic filter function using ExpressionTree .. I want to share with you guys ...

Start

 var allFiltered= Filter(AllCustomer, "Name", "Moumit"); public static List<T> Filter<T>(this List<T> Filterable, string PropertyName, object ParameterValue) { ConstantExpression c = Expression.Constant(ParameterValue); ParameterExpression p = Expression.Parameter(typeof(T), "xx"); MemberExpression m = Expression.PropertyOrField(p, PropertyName); var Lambda = Expression.Lambda<Func<T, Boolean>>(Expression.Equal(c, m), new[] { p }); Func<T, Boolean> func = Lambda.Compile(); return Filterable.Where(func).ToList(); } 

One More

 string singlePropertyName=GetPropertyName((Property.Customer p) => p.Name); public static string GetPropertyName<T, U>(Expression<Func<T, U>> expression) { MemberExpression body = expression.Body as MemberExpression; // if expression is not a member expression if (body == null) { UnaryExpression ubody = (UnaryExpression)expression.Body; body = ubody.Operand as MemberExpression; } return string.Join(".", body.ToString().Split('.').Skip(1)); } 

Make it more expandable

 string multiCommaSeparatedPropertyNames=GetMultiplePropertyName<Property.Customer>(c => c.CustomerId, c => c.AuthorizationStatus) public static string GetMultiplePropertyName<T>(params Expression<Func<T, object>>[] expressions) { string[] propertyNames = new string[expressions.Count()]; for (int i = 0; i < propertyNames.Length; i++) { propertyNames[i] = GetPropertyName(expressions[i]); } return propertyNames.Join(); } 

....... I know that this can also be done using Reflection ... but it is very fast or I can say that it is equivalent to Lambda after the first compilation ... The very first iteration is only an average of 10 milliseconds slower. .. So this is the magic of the Expression Tree . Simple and fantastic .... I think ... !!!!!!!!

+12
Dec 09 '13 at 11:57
source share

I use them to create dynamic queries, whether sorting or filtering data. As an example:

 IQueryable<Data.Task> query = ctx.DataContext.Tasks; if (criteria.ProjectId != Guid.Empty) query = query.Where(row => row.ProjectId == criteria.ProjectId); if (criteria.Status != TaskStatus.NotSet) query = query.Where(row => row.Status == (int)criteria.Status); if (criteria.DueDate.DateFrom != DateTime.MinValue) query = query.Where(row => row.DueDate >= criteria.DueDate.DateFrom); if (criteria.DueDate.DateTo != DateTime.MaxValue) query = query.Where(row => row.DueDate <= criteria.DueDate.DateTo); if (criteria.OpenDate.DateFrom != DateTime.MinValue) query = query.Where(row => row.OpenDate >= criteria.OpenDate.DateFrom); var data = query.Select(row => TaskInfo.FetchTaskInfo(row)); 
+11
Dec 31 '09 at 15:38
source share

LINQ providers are mainly implemented by processing expression trees. I also use them to remove literal strings from my code:

+7
Dec 31 '09 at 14:49
source share

I used an expression tree to build an evaluator of a mathematical expression: Building an expression evaluator with expression trees in C #

+5
Oct 12 '12 at 11:44
source share

You can use them to create your own linq provider for a website such as Google or Flickr or Amazon, your own website, or another data provider.

+4
Dec 31 '09 at 14:47
source share

Originally by Jomo Fisher , Gustavo Guerra published a revised version of the static string dictionary .

Where through expression trees is a dynamic expression that provides a truly (readable: funny) dictionary.

The implementation creates a dynamic decision tree that selects the root value according to the length of the input string, then the first letter, then the second letter, etc.

This ultimately works much faster than the equivalent dictionary.

+2
Dec 31 '09 at 16:06
source share



All Articles