If condition in LINQ Where clause
Solution 1
var query = someList.Where(a => (someCondition)? a == "something" : true);
so, if 'someCondition' is false, 'Where' will be skipped.
Solution 2
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.
Solution 3
Make use of WhereIf
extenstion method avaialbe in linq
Example
if (SearchControlMain.PostingID.HasValue)
query = query.Where(q => q.PostingID == SearchControlMain.PostingID);
instead of above go for the below
query = query.WhereIf(SearchControlMain.CategoryID.HasValue, q => q.CategoryID == SearchControlMain.CategoryID);
LINQ to SQL Where Clause Optional Criteria
Solution 4
Not sure if this is appropriate but it is quite useful, you can use ifs quite handily with conditional where clauses:
var r = (from p in productinfo.tblproduct
where p.Accountid == accountid
select p);
if (uuf1 != null)
r = r.Where(p => p.UnitUserField1 == uuf1);
if (uuf2!= null)
r = r.Where(p => p.UnitUserField2 == uuf2);
So the where clause will be amended according to what is in UUF1 or UUF2 i.e. you might have only UUF1 with info, in which case it will take that and ignore the UUF2 where clause, you might have both in which it will take both or you might not have anything in UUF1 or 2 and your where clause will just take the accountid as the where clause.
Solution 5
In my case there were two "conditional" where depending on search keys, so I did:
var query = db.Package.Include("SomeThing")
.Where(item => searchString1 == null || searchString1 == "" || item.Contains(searchString1))
.Where(item => searchString2 == null || searchString2 == "" || item.Contains(searchString2));
...
Hasan
Updated on February 18, 2022Comments
-
Hasan about 2 years
With Linq, can I use a conditional statement inside of a
Where
extension method? -
Mel Gerats over 13 yearsWhich is equal to: list.Where(item => Foo(item));
-
Omer about 7 yearsWhere is not producing IQueryable, it is producing IEnumerable. Wrong answer
-
D Hansen over 6 years@OmerK Where does in-fact product IQueryable, if the object you are running the extension method on is also an IQueryable, if you run it on an IEnumerable, you will get an IEnumerable.
-
logical8 almost 6 yearsAnalog (little shorter):
var query = someList.Where(a => !someCondition || a == "something");
-
itmuckel about 2 yearsThis is only viable if you don't need the element's value in the condition.