Multiple Conditions in Lambda Expressions at runtime C#
- by Ryan
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