Вопрос

I write whereIn extension method:

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

I can call this look like it:

List<int> paymentTypeIds;

IQueryable<Order> iq = Entity.Order.AsQueryable();

iq = iq.WhereIn(h => h.PaymentType.Id, paymentTypeIds);

But I want to pass another parameter to my WhereIn code. I want to working it look like it:

iq = iq.WhereIn(h => h.PaymentType.Id || h.Bank.Id, paymentTypeIds);

How can I do this?

Это было полезно?

Решение

You can't use the syntax h => h.PaymentType.Id || h.Bank.Id, because int || int isn't defined. You could use params to easily pass in multiple expressions. Note that params has to be the last in the parameter list, so I swapped the order.

public static IQueryable<T> WhereIn<T, TValue>(this IQueryable<T> query,
  IEnumerable<TValue> values,
  params Expression<Func<T, TValue>>[] valueSelectors)

You'd use it like:

iq = iq.WhereIn(paymentTypeIds, h => h.PaymentType.Id, h => h.Bank.Id);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top