Reputation: 15583
I need something like this: Select name from users where id = 1 or id = 2
.
I know I can do this:
_db.Users
.Where(u => u.Id == 1 || u.Id == 2);
But is there any alternative to this? Is there something like this:
_db.User
.Where(u => u.Id == 1)
.Or
.Where(u => u.Id == 2)
Upvotes: 0
Views: 150
Reputation: 2548
I usually use next form to build dynamic linq with ORs and ANDs.
public class Linq
{
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expression1,
Expression<Func<T, bool>> expression2)
{
if (expression1 == null) throw new ArgumentNullException("expression1", "Consider setting expression1 to Linq.True<T>() or Linq.False<T>()");
var invokedExpr = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse(expression1.Body, invokedExpr), expression1.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expression1,
Expression<Func<T, bool>> expression2)
{
if (expression1 == null) throw new ArgumentNullException("expression1", "Consider setting expression1 to Linq.True<T>() or Linq.False<T>()");
var invokedExpr = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.AndAlso(expression1.Body, invokedExpr), expression1.Parameters);
}
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
}
And then use it in your code:
Expression<Func<User, bool>> searchExpression = Linq.False<User>();
searchExpression = Linq.Or<User>(searchExpression, b => b.Id==1);
searchExpression = Linq.Or<User>(searchExpression, b => b.Id==2);
Then you use this searchExpression as
_db.Users.Where(searchExpression);
With this form it is very easy to build dynamic queries, like:
Expression<Func<User, bool>> searchExpression = Linq.False<User>();
searchExpression = Linq.Or<User>(searchExpression, b => b.Id==1);
if (!String.IsNullOrEmpty(name))
searchExpression = Linq.Or<User>(searchExpression, b => b.Name.StartsWith(name));
//combine with OR / AND as much as you need
It will generate only one query to the DB.
Upvotes: 2
Reputation: 16740
You just want:
_db.Users.Where(u => (u.Id == 1 || u.Id == 2));
Upvotes: 0
Reputation:
Not directly. Remember, _db.Users.Where(u => u.Id == 1)
is the user whose id is 1. You cannot get the user with id 2 from that, because it isn't there.
You can use some other approach, such as
var user1 = _db.Users.Where(u => u.Id == 1);
var user2 = _db.Users.Where(u => u.Id == 2);
var users = user1.Union(user2);
or
var userids = new int[] { 1, 2 };
var users = _db.Users.Where(u => userids.Contains(u.Id));
though.
Upvotes: 2