I am trying to build up an expression tree that I can feed into Linq2SQL so that it will generate a nice clean query. My purpose is to build a filter that takes an arbitrary
this example might help you. I guess the best is to build the expression without lambdas:
public class Entity
{
public Entity(string someField)
{
SomeField = someField;
}
public string SomeField { get; set; }
}
class Program
{
static void Main(string[] args)
{
var entities = new[] {new Entity("fooBar"), new Entity("barBaz"), new Entity("baz"), new Entity("foo")};
entities.Where(BuildExpression("ar","az").Compile())
.ToList()
.ForEach(e => Console.WriteLine(e.SomeField));
Console.ReadLine();
}
public static Expression> BuildExpression(params string[] words)
{
var parameter = Expression.Parameter(typeof (Entity));
var matchs = words.Select(word =>
{
var property = Expression.Property(parameter, "SomeField");
var toLower = Expression.Call(property, "ToLower", new Type[] {});
var contains = Expression.Call(toLower, "Contains",
new Type[]{},
Expression.Constant(word));
return contains;
}).OfType();
var body = matchs.Aggregate(Expression.Or);
return Expression.Lambda>(body, new[] {parameter});
}
}
Please let me know if I should add more information to this answer.