Reputation: 12283
I want to build a System.Linq.Expression from the string List like this:
System.Linq.Expressions.Expression x = null;
foreach (string s in GetWords(input))
{
/* Create Expression */
}
so I could use:
.Where(x =>
x.Name.Like(string.Format("%{0}%", word1)) ||
x.Name.Like(string.Format("%{0}%", word2)) ||
x.Name.Like(string.Format("%{0}%", word3)) ||
x.Id.ToString().Like(string.Format("%{0}%", word1)) ||
x.Id.ToString().Like(string.Format("%{0}%", word2)) ||
x.Id.ToString().Like(string.Format("%{0}%", word3)) ||
);
x
is MyObject
Upvotes: 3
Views: 1284
Reputation: 1062600
Something like:
string[] words = { "foo", "bar", "blop" }; // your data
Expression body = null;
var param = Expression.Parameter(typeof(SomeType), "x");
var id = Expression.PropertyOrField(param, "Id");
var name = Expression.PropertyOrField(param, "Name");
foreach (string word in words)
{
var wordExpr = Expression.Constant(word, typeof(string));
var wordTest = Expression.OrElse(
Expression.Call(id, "Contains", null, wordExpr),
Expression.Call(name, "Contains", null, wordExpr));
body = body == null ? wordTest : Expression.OrElse(body, wordTest);
}
Expression<Func<SomeType,bool>>lambda;
if (body == null) { lambda = x => false; }
else { lambda = Expression.Lambda<Func<SomeType, bool>>(body, param); }
Upvotes: 3