1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public static class QueryableExtensions
{
private static Expression<Func<TElement, bool>> GetWhereInExpression<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(GetWhereInExpression(propertySelector, values));
}
public static IQueryable<TElement> WhereIn<TElement, TValue>(
this IQueryable<TElement> source, Expression<Func<TElement, TValue>> propertySelector, IEnumerable<TValue> values)
{
return source.Where(GetWhereInExpression(propertySelector, values));
} |
Partager