0

Possible Duplicate:
Linq: “Or” equivalent of Where()

I posted a question about a week ago where the solution to append to a LINQ query based on if my parameters had values in them looked like:

var query = Database.Set<User>();

if (condition1.HasValue)
{
    query = query.Where(x => x.Condition1 == condition1.Value);
}
if (condition2.HasValue)
{
    query = query.Where(x => x.Condition2 == condition2.Value);
}
...
return query.ToList();

This code would append to the WHERE clause using AND. How would I go about appending to the WHERE clause using OR instead?

Community
  • 1
  • 1
Thomas
  • 5,888
  • 7
  • 44
  • 83
  • 4
    It looks like this will probably help: http://stackoverflow.com/questions/2101540/linq-or-equivalent-of-where – David Burhans Nov 23 '11 at 16:07
  • 1
    You asked me a question in a comment. I then replied to it in the comment - did you read that and follow the link before asking this question? – Jon Skeet Nov 23 '11 at 16:08
  • I checked the comment before posting but there was no answer yet so I figured I would post a new question. I will take a look now. Thanks. – Thomas Nov 23 '11 at 16:11

5 Answers5

4

You'll want to use a predicate builder, here is an example

JonH
  • 32,732
  • 12
  • 87
  • 145
2

You could try using the PredicateBuilder library. Here's a sample:

var predicate = PredicateBuilder.False<User>();
if (condition1.HasValue)
{
  predicate = predicate.Or(x => x.Condition1 == condition1.Value);
}
if (condition2.HasValue)
{
  predicate = predicate.Or(x => x.Condition2 == condition2.Value);
}
return Database.Set<User>().Where(predicate);
Tevin
  • 1,394
  • 16
  • 26
1

This would do the trick, as an alternative to PredicateBuilder.

var query = Database.Set<User>();             
var query2 = query.Where(x => (condition1.HasValue && x.Condition1 == condition1.Value) || (condition2.HasValue && x.Condition2 == condition2.Value));
daniloquio
  • 3,822
  • 2
  • 36
  • 56
0

You have to create expression tree yourself for this. Or the other way, you can use Dynamic LINQ and construct LINQ quesry string and execute it. Look at System.Linq.Expression names, or System.Linq.Dynamic

Vladimir Perevalov
  • 4,059
  • 18
  • 22
0

You can't. Explanation:

var iS = {1,2,3,4,5};
var iEvens = iS.Where(x => x % 2 == 0);
var iEvensAddOr = iEvens.OrWhere(x => x % 2 == 1);

You expect to have iS.Where(x => x % 2 == 0 || x % 2 == 1), but you have already filtered your list with the first Where(). What you want would be to undo the filter and create a new one. But you have already filtered, it's too late.

You can use a union, but it's not exactly what you want.

hammar
  • 138,522
  • 17
  • 304
  • 385
Iesvs
  • 11