Since neither of these seem to work...
x => guids.Contains(x.Guid)
x => guids.Any(y => y == x.Guid)
... we write a custom lambda expression builder that generates:
x => x.Id == {id1} OR x.Id == {id2} OR x.Id == {id3}
This is a trivial scenario, but demonstrates how GetContainsId<User>(ids, repo)
will find all Users with an Id that matches something in the supplied list.
public List<T> GetContainsId<T>(List<int> ids, SimpleRepository repo)
where T : Record, new() // `Record` is a base class with property Id
{
ParameterExpression x = Expression.Parameter(typeof(T), "x");
LambdaExpression expr;
if (ids.Count == 0)
{
expr = Expression.Lambda(LambdaExpression.Constant(false), x);
}
else
{
expr = Expression.Lambda(BuildEqual(x, ids.ToArray()), x);
}
return repo.Find<T>((Expression<Func<T,bool>>)expr).ToList();
}
private BinaryExpression BuildEqual(ParameterExpression x, int id)
{
MemberExpression left = Expression.Property(x, "Id");
ConstantExpression right = Expression.Constant(id);
return Expression.Equal(left, right);
}
private BinaryExpression BuildEqual(ParameterExpression x, int[] ids, int pos = 0)
{
int id = ids[pos];
pos++;
if (pos == ids.Length)
{
return BuildEqual(x, id);
}
return Expression.OrElse(BuildEqual(x, ids, pos), BuildEqual(x, id));
}