Multiple Conditions in Lambda Expressions at runtime C#
Posted
by Ryan
on Stack Overflow
See other posts from Stack Overflow
or by Ryan
Published on 2010-03-21T11:30:59Z
Indexed on
2010/03/21
12:21 UTC
Read the original article
Hit count: 698
lambda-expressions
|c#
Hi,
I would like to know how to be able to make an Expression tree by inputting more than one parameter
Example:
dataContext.Users.Where(u => u.username == "Username" && u.password == "Password")
At the moment the code that I did was the following but would like to make more general in regards whether the condition is OR or AND
public Func<TLinqEntity, bool> ANDOnlyParams(string[] paramNames, object[] values)
{
List<ParameterExpression> paramList = new List<ParameterExpression>();
foreach (string param in paramNames)
{
paramList.Add(Expression.Parameter(typeof(TLinqEntity), param));
}
List<LambdaExpression> lexList = new List<LambdaExpression>();
for (int i = 0; i < paramNames.Length; i++)
{
if (i == 0)
{
Expression bodyInner = Expression.Equal(
Expression.Property(
paramList[i], paramNames[i]),
Expression.Constant(values[i]));
lexList.Add(Expression.Lambda(bodyInner, paramList[i]));
}
else
{
Expression bodyOuter = Expression.And(
Expression.Equal(
Expression.Property(
paramList[i], paramNames[i]),
Expression.Constant(values[i])),
Expression.Invoke(lexList[i - 1], paramList[i]));
lexList.Add(Expression.Lambda(bodyOuter, paramList[i]));
}
}
return ((Expression<Func<TLinqEntity, bool>>)lexList[lexList.Count - 1]).Compile();
}
Thanks
© Stack Overflow or respective owner