Σελίδα 1 από 1

QueryExtensions IsIn / NotIsIn

Δημοσιεύτηκε: Τρί Φεβ 08, 2022 6:43 am
από GeoB
public static IQueryable<TElement> IsIn<TElement, TValue>(this IQueryable<TElement> source, Expression<Func<TElement, TValue>> propertySelector, params TValue[] values) => source.Where(WhereInExpression(propertySelector, values));
public static IQueryable<TElement> IsIn<TElement, TValue>(this IQueryable<TElement> source, Expression<Func<TElement, TValue>> propertySelector, IEnumerable<TValue> values) => source.Where(WhereInExpression(propertySelector, values));
private static Expression<Func<TElement, bool>> WhereInExpression<TElement, TValue>(Expression<Func<TElement, TValue>> propertySelector, IEnumerable<TValue> values) {
var p = propertySelector.Parameters.Single();
var list = values as IList<TValue> ?? values.ToList();
if (!list.Any()) return x => false;
var e = list.Select(value => (Expression)Expression.Equal(propertySelector.Body, Expression.Constant(value, typeof(TValue))));
var body = e.Aggregate(Expression.Or);
return Expression.Lambda<Func<TElement, bool>>(body, p);
}

public static IQueryable<TElement> NotIsIn<TElement, TValue>(this IQueryable<TElement> source, Expression<Func<TElement, TValue>> propertySelector, params TValue[] values) => source.Where(GetWhereNotInExpression(propertySelector, values));
public static IQueryable<TElement> NotIsIn<TElement, TValue>(this IQueryable<TElement> source, Expression<Func<TElement, TValue>> propertySelector, IEnumerable<TValue> values) => source.Where(GetWhereNotInExpression(propertySelector, values));
private static Expression<Func<TElement, bool>> GetWhereNotInExpression<TElement, TValue>(Expression<Func<TElement, TValue>> propertySelector, IEnumerable<TValue> values) {
var p = propertySelector.Parameters.Single();
var list = values as IList<TValue> ?? values.ToList();
if (!list.Any()) return x => false;
var e = list.Select(value => (Expression)Expression.NotEqual(propertySelector.Body, Expression.Constant(value, typeof(TValue))));
var body = e.Aggregate(Expression.And);
return Expression.Lambda<Func<TElement, bool>>(body, p);
}

Re: QueryExtensions IsIn / NotIsIn

Δημοσιεύτηκε: Τρί Φεβ 08, 2022 6:48 am
από GeoB
Usage:

var q = from t in db.T
join p in db.P.IsIn( f => f.Idx, AnyList() ) on mp.PID equals p.PID
select t;

var q = from t in db.T
join p in db.P.NotIsIn( f => f.Idx, AnyList() ) on mp.PID equals p.PID
select t;

var q = from p in db.P.IsIn(x => x.Cat, 101, 107, 112).IsIn(x => x.Tipo, 1231, 2235, 3237, 4247)
select p;

var q = from p in db.P.NoIsIn(x => x.Cat, 101, 107, 112).NotIsIn(x => x.Tipo, 1231, 2235, 3237, 4247)
select p;