Practical use of expression trees [closed]
Solution 1:
As Jon notes, I use them to provide generic operators with .NET 3.5. I also use them (again in MiscUtil) to provide fast access to non-default constructors (you can't use Delegate.CreateDelegate
with constructors, but Expression
works fine).
Other uses of manually created expression trees:
- object cloning
- dynamic LINQ sorting
- as a compiler
But really, Expression is a very versatile way of writing any dynamic code. Much simpler than Reflection.Emit
, and for my money, simpler to understand than CodeDOM. And in .NET 4.0, you have even more options available. I show the fundamentals of writing code via Expression
on my blog.
Solution 2:
Marc Gravell has used them to great effect in MiscUtil to implement generic operators.
Solution 3:
I just created a generic filter function using an Expression Tree that 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 it also can be done using reflection, but this one is tremendously fast or, I can say, equivalent to a lambda after first compilation. The very first iteration takes just an average of 10 milliseconds. So this is Expression Tree magic. Simple and fantastic (I think)!