现在的位置: 首页 > 综合 > 正文

Entity framework WhereInExtension

2012年11月30日 ⁄ 综合 ⁄ 共 849字 ⁄ 字号 评论关闭

摘自 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));
}
}

抱歉!评论已关闭.