tags:

views:

154

answers:

1

Hi!

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

+2  A: 

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); }
Marc Gravell
(and use `.Where(lambda)`)
Marc Gravell
you mean lambda.compile()?
PaN1C_Showt1Me
Only if you are using LINQ-to-Objects; byt you asked how to get an Expression (which is what the above does), not a delegate (which is what `Compile()` does). If you are just using LINQ-to-Objects there are better ways that don't involve `Expression`. Let me know...
Marc Gravell
I'm using it for IQueryable<T>.Where(...). But I use an ORMapper that transformates the where condition directly into sql. And with non-compiled version does it not work..
PaN1C_Showt1Me
If you need to use `Compile()` for it to *compile*, then you are actually using `IEnumerable<T>.Where`, which is very different. It it compiles but doesn't run, then let me know. That would be odd.
Marc Gravell