With Linq, can I use a conditional statement inside of a Where
extension method?
var query = someList.Where(a => (someCondition)? a == "something" : true);
so, if 'someCondition' is false, 'Where' will be skipped.
Yes you can like:
var query = someList.Where(a => a == "something"); if (condition) { query = query.Where(b => b == "something else"); } var result = query.ToList();
Because Where
is producing an IQueryable
, the execution is deferred until the ToList
in my example so you can chain Where
s together as much as you want and then just execute it after you have passed all your conditions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With