由於這些都不似乎工作...
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));
}
可恥的是他們......它不喜歡搶不知道 http://blog.wekeroad.com/blog/creating-in-queries-with-linq-to -sql/ – jvenema 2010-05-20 17:24:49