Conditional WHERE in LINQ

c# entity-framework linq linq-to-entities tsql

Question

Hi any suggestions on building a LINQ statement based on search criteria?

I'll be passing in an instance of a 'SearchCriteria' class with all parameters nullable.

I then want to

if (sc.a != null)
    // add to where

if (sc.b != null)
    // add to where

The key thing is these are to be ORs not ANDs.

Any tips?

And for bonus points I'd like to use 'contains' on an int? but I can only get equals or not equals.

1
6
9/9/2012 8:51:18 AM

Accepted Answer

Try:

.Where(x =>
    (x.a != null ? x.a == a : false) &&
    (x.b != null ? x.b == b : false));

or

.Where(x =>
    (x.a != null && x.a == a) ||
    (x.b != null && x.b == b));

Also:

.Where(x => new int[] { 1, 2, 3 }.Contains(x.i));
5
9/9/2012 8:49:59 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow