Adding or to linq query

Viewed 756

It is possible to add or to linq query after declaration?

I mean if i have :

Query.Where(f => some-condition ); 

I wand to add "OR" after that:

if (some-condition) 
   Query.WhereOr(f => some-condition ); 
3 Answers

Looks like you could be looking for a Predicate builder Or you can just stack some .Where clause as linq is lazy.

As your question lacks of context, imagine querying a Person table based on a form (2 fields/1 checkbox).

// Where Stacking
if (!string.IsNullOrEmpty(FieldA.Text))
{// OR
    result = query.Where(item => item.Something.Contains(FieldA.Text));
}
if (!string.IsNullOrEmpty(FieldB.Text))
{// AND
    result = result.Where(item => item.SomethingElse.Contains(FieldB.Text));
}

// Predicate
if (CheckBox1.Checked || CheckBox2.Checked || CheckBox3.Checked))
{//Here your initialise your predicate to false because you are going to do OR
    var predicate = PredicateBuilder.False<SearchItem>();
    if(CheckBox1.Checked) predicate = predicate.Or(item => item.Foo == 1);
    if(CheckBox2.Checked) predicate = predicate.Or(item => item.Foo == 2);
    if(CheckBox3.Checked) predicate = predicate.Or(item => item.Foo == 3);
    result = result.Where(predicate);
}

Stacking Where is a good solution but can produce a little overheat but nothing that is really noticable.

PS: Article of Jon about nesting where https://codeblog.jonskeet.uk/2011/06/16/linq-to-objects-and-the-performance-of-nested-quot-where-quot-calls/

You should use LinqKit.PredicateBuilder class

Example:

var predicate = PredicateBuilder.True<Product>();
if(inputPrice > 100)
   predicate = predicate.And (p => p.Price > 100);
if(inputName == "S%")
   predicate = predicate.And (p => p.Name.StartsWith("S"));

Finally,

var result = products.Where(predicate);

More details Wiki

IEnumerable and IQueryable to some extent will allow you to chain conditions

Query.Where(f=> some-condition || some_other_condition);
// or
var q = Query.Where(f=> some-condition)
if(stuff_needs_to_happen)
  q = q.Where(f => stuff_that_needs_to_happen)

The reason for the "to some extent" is that with IQueryable the underlying query language may not support some of the conditions in the predicate (custom functions and so on).

Related