我写了whereIn扩展方法:
public static IQueryable<T> WhereIn<T, TValue>(this IQueryable<T> query,
Expression<Func<T, TValue>> valueSelector,
IEnumerable<TValue> values)
{
return query.Where(BuildContainsExpression(valueSelector, values));
}
private static Expression<Func<TElement, bool>> BuildContainsExpression<TElement, TValue>(
Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values)
{
if (null == valueSelector)
{
throw new ArgumentNullException("valueSelector");
}
if (null == values)
{
throw new ArgumentNullException("values");
}
ParameterExpression p = valueSelector.Parameters.Single();
TValue[] enumerable = values as TValue[] ?? values.ToArray();
if (!enumerable.Any())
{
return e => false;
}
IEnumerable<Expression> equals =
enumerable.Select(
value =>
(Expression) Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof (TValue))));
Expression body = equals.Aggregate(Expression.Or);
return Expression.Lambda<Func<TElement, bool>>(body, p);
}
我可以称之为:
List<int> paymentTypeIds;
IQueryable<Order> iq = Entity.Order.AsQueryable();
iq = iq.WhereIn(h => h.PaymentType.Id, paymentTypeIds);
但我想将另一个参数传递给我的WhereIn
代码。我想看起来像它:
iq = iq.WhereIn(h => h.PaymentType.Id || h.Bank.Id, paymentTypeIds);
我该怎么做?
答案 0 :(得分:0)
您无法使用h => h.PaymentType.Id || h.Bank.Id
语法,因为int || int
未定义。您可以使用params
轻松传入多个表达式。请注意,params
必须是参数列表中的最后一个,因此我交换了订单。
public static IQueryable<T> WhereIn<T, TValue>(this IQueryable<T> query,
IEnumerable<TValue> values,
params Expression<Func<T, TValue>>[] valueSelectors)
您可以像以下一样使用它:
iq = iq.WhereIn(paymentTypeIds, h => h.PaymentType.Id, h => h.Bank.Id);