In .net (c# or vb) expressions, how would you implement SQL\'s handy IN() functionality?
i.e. value in (1, 2, 4, 7)
rather than:
value = 1 or value =
Here's some simple Linq with some pseudo code. No need to re-invent the wheel.
int[] values = new int[]{1, 2, 4, 7};
int target = 2;
bool contains = values.Any(v => v == target);
Or use .Contains
as some have suggested.
I know there are LOADS of answers here, but here's my take on the subject, used daily in SubSonic. it's an extension method:
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));
}
and 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));
}
usage:
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);
this really makes me smile every time i review it :)
jim
[edit] - originally sourced from here on SO but modified to use iqueryable and params: 'Contains()' workaround using Linq to Entities?
You can use Contains() method on the list.
int myValue = 1;
List<int> checkValues = new List<int> { 1, 2, 3 };
if (checkValues.Contains(myValue))
// Do something