Search code examples
c#linqexpression-trees

Expression tree to split property value


I am working with linq expression trees (http://msdn.microsoft.com/en-us/library/vstudio/bb397951.aspx) to create complex, dynamically created custom filters. Now I need to create an expression, that compares not the property of my table, but every part of my split property.

The corresponding static linq statement would be:

myContext.MyEntityCollection
 .Where(item => item.MyProperty != null)
 .AsEnumerable<MyEntity>()
 .Select(item => item.MyProperty.Split(new[] { ',' })
 .Where( .. my filter ..)

E.g. on this input

Table MyEntity
Id          MyProperty
-----------------------------------
1           part1,part2,part3,part4
2           part5,part6

I want to search for "part3" and get the first row.

How to create the lambda expression for the split func<>?

UPDATE: That's the status I got so far (at the last line I get stuck). Also I was trying to built the expression tree from the linq statement above with the ExpressionTreeViewer but it does not work, I think because of the ".AsEnumerable".

ParameterExpression param = Expression.Parameter(typeof(ReportIndex), "MyEntity");
MemberExpression stringProperty = Expression.Property(param, "MyProperty");
MethodInfo mi = typeof(string).GetMethod("Split", new[] { typeof(char[]) });
MethodCallExpression splitExpression = 
    Expression.Call(exDateProperty, mi, Expression.Constant(new[] { '|' }));
MethodInfo containsMethod = typeof(ICollection<string>).GetMethod("Contains");
var expression = Expression.Call(param, containsMethod, splitExpression, stringProperty);

Solution

  • After many tries, I think it is not possible to do with expression trees. What I finally did, was to change my data model.

    UPDATE Since there is no new input for one week, I set this as answer.