Tôi biết có vô số câu trả lời ở đây, nhưng đây là quan điểm của tôi về đề tài này, được sử dụng hàng ngày trong cận âm. nó là một phương pháp khuyến nông:
public static IQueryable<T> WhereIn<T, TValue>(
this IQueryable<T> query,
Expression<Func<T, TValue>> selector,
params TValue[] collection) where T : class
{
if (selector == null) throw new ArgumentNullException("selector");
if (collection == null) throw new ArgumentNullException("collection");
ParameterExpression p = selector.Parameters.Single();
if (!collection.Any()) return query;
IEnumerable<Expression> equals = collection.Select(value =>
(Expression)Expression.Equal(selector.Body,
Expression.Constant(value, typeof(TValue))));
Expression body = equals.Aggregate(Expression.Or);
return query.Where(Expression.Lambda<Func<T, bool>>(body, p));
}
và WhereNotIn:
public static IQueryable<T> WhereNotIn<T, TValue>(
this IQueryable<T> query,
Expression<Func<T, TValue>> selector,
params TValue[] collection) where T : class
{
if (selector == null) throw new ArgumentNullException("selector");
if (collection == null) throw new ArgumentNullException("collection");
ParameterExpression p = selector.Parameters.Single();
if (!collection.Any()) return query;
IEnumerable<Expression> equals = collection.Select(value =>
(Expression)Expression.NotEqual(selector.Body,
Expression.Constant(value, typeof(TValue))));
Expression body = equals.Aggregate(Expression.And);
return query.Where(Expression.Lambda<Func<T, bool>>(body, p));
}
sử dụng:
var args = new [] { 1, 2, 3 };
var bookings = _repository.Find(r => r.id > 0).WhereIn(x => x.BookingTypeID, args);
// OR we could just as easily plug args in as 1,2,3 as it's defined as params
var bookings2 = _repository.Find(r => r.id > 0).WhereIn(x => x.BookingTypeID, 1,2,3,90);
var bookings3 = _repository.Find(r => r.id > 0).WhereNotIn(x => x.BookingTypeID, 20,30,60);
điều này thực sự khiến tôi mỉm cười mỗi khi tôi xem lại nó :)
jim
[sửa] - ban đầu có nguồn gốc từ đây trên SO nhưng sửa đổi để sử dụng params IQueryable và: 'Contains()' workaround using Linq to Entities?
phiên bản .NET framework nào? –
Tôi chủ yếu sử dụng 3.5. Bạn không chắc chắn nếu có anthing trong 4.0 mà làm cho điều này dễ dàng hơn? –