0

Normally when we have a grid result with multiple possible filters we may use a logic similar to this one:

var query = db.Something;
if(isFilter1 != null)
     query = query.Where(x=>x.Prop1 == isFilter1);
}
if(isFilter2 != null)
     query = query.Where(x=>x.Prop2 == isFilter2);
}
.... etc...
var finalResult = query.ToList();

But now I would like to use this kind of logic but using "OR" and not only "AND". A simple example of the "end result of the query" that I want to achive.

var finalResult = db.Something.Where(x => 
           x.Prop1 == null && 
           x.Prop2 != 0 && 
           x.Prop3 == id && 
           (x.Prop4 == "String1" || x.Prop4== "String2" || x.Prop4== "String3"));
Dryadwoods
  • 2,875
  • 5
  • 42
  • 72
  • LINQ to what are you using? LINQ to entities? objects? SQL? – Benjamin Gruenbaum May 06 '13 at 07:42
  • @GertArnold is not duplicated question, at least not with you one you are pointing, because my question is to learn on how to use a loop to add new Where clauses BEFORE hiting the Database with the query. – Dryadwoods May 06 '13 at 07:49
  • 1
    You are only "hitting the database" when you iterate your resultset in the ToList() call. You can add a million conditionals dynamically and the query will still not run. Only when you start working with the data will the data be retrieved. Look up the concept of "lazy loading" for more on this type of thing. – Captain Kenpachi May 06 '13 at 07:52
  • Please read my updated question.... – Dryadwoods May 06 '13 at 07:54
  • 1
    If you inspect the actual SQL generated by what you want versus what Cuong Le proposed, you will see that they will be identical. a List.Contains() and a number of OR statements are exactly the same thing when translated into SQL. The Contains() method is used in exactly the instance where you don't know the number of arguments beforehand. – Captain Kenpachi May 06 '13 at 07:58
  • 1
    @Dryadwoods As Juann says, you're not hitting the database while adding predicates to it. Linqkit is becoming a _de facto_ standard for this kind of tasks. An alternative for dynamic `OR`s is expanding your query with `Union`s, but that's less attractive because it produces a less efficient query plan. – Gert Arnold May 06 '13 at 08:23

1 Answers1

2

You can use Contains method:

var list = new[] { "string1", "string2", "string3"};

var finalResult = db.Something.Where(x => 
       x.Prop1 == null && 
       x.Prop2 != 0 && 
       x.Prop3 == id && list.Contains(x.Prop4));
cuongle
  • 74,024
  • 28
  • 151
  • 206
  • Thanks for the answer but that is not what I am looking for, ANY, or INCLUDE, or similar are not what I am looking for. – Dryadwoods May 06 '13 at 07:45