由于这些似乎都不起作用......
x => guids.Contains(x.Guid)
x => guids.Any(y => y == x.Guid)
...我们编写了一个自定义 lambda 表达式构建器,它生成:
x => x.Id == {id1} OR x.Id == {id2} OR x.Id == {id3}
这是一个简单的场景,但演示了如何GetContainsId<User>(ids, repo)
找到 ID 与提供的列表中的某些内容匹配的所有用户。
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));
}