Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If condition in LINQ Where clause

Tags:

linq

where

With Linq, can I use a conditional statement inside of a Where extension method?

like image 912
Hasan Avatar asked Sep 10 '10 07:09

Hasan


2 Answers

var query = someList.Where(a => (someCondition)? a == "something" : true); 

so, if 'someCondition' is false, 'Where' will be skipped.

like image 138
logical8 Avatar answered Sep 29 '22 09:09

logical8


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 Wheres together as much as you want and then just execute it after you have passed all your conditions.

like image 28
Kelsey Avatar answered Sep 29 '22 07:09

Kelsey