Entity framework WhereInExtension

摘自 http://www.cnblogs.com/ejiyuan/archive/2009/07/20/1527224.html

public static class WhereInExtension
{
private static Expression<Func<TElement, bool>> BuildWhereInExpression<TElement, TValue>(Expression<Func<TElement, TValue>> propertySelector, IEnumerable<TValue> values)
{
ParameterExpression p
= propertySelector.Parameters.Single();
if (!values.Any())
return e => false;

var equals
= values.Select(value => (Expression)Expression.Equal(propertySelector.Body, Expression.Constant(value, typeof(TValue))));
var body
= equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal));

return Expression.Lambda<Func<TElement, bool>>(body, p);
}

public static IQueryable<TElement> WhereIn<TElement, TValue>(this IQueryable<TElement> source, Expression<Func<TElement, TValue>> propertySelector, params TValue[] values)
{
return source.Where(BuildWhereInExpression(propertySelector, values));
}
}

posted @ 2011-04-14 17:03  梦幻泡影  阅读(330)  评论(0编辑  收藏  举报