Conditional WHERE in LINQ

Hi, any suggestions for creating a LINQ statement based on your search criteria?

I will pass an instance of the "SearchCriteria" class with all parameters that allow a null value.

Then i want

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

The key point is that it is OR, not AND.

Any tips?

And for bonus points would I like to use 'contains' in int? but I can only get equal or not equal.

+6
source share
1 answer

Try:

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

or

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

also:

 .Where(x => new int[] { 1, 2, 3 }.Contains(xi)); 
+4
source

Source: https://habr.com/ru/post/924945/


All Articles