如何用Value1,Value2编写Linq WhereIn

时间:2014-05-05 13:25:22

标签: c# sql linq entity-framework linq-to-entities

我写了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);

我该怎么做?

1 个答案:

答案 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);