tags:

views:

80

answers:

4

Can I use if clause with Linq where?

+2  A: 

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.

Kelsey
+1 Best answer out of the three.
Christian Hayter
A: 

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 WhereIf Extension Method

LINQ to SQL Where Clause Optional Criteria

Pranay Rana
A: 

I'm not sure what the question is, but a possible answer could be:

Yes,

list.Where(item => { if (Foo(item)) return true; else return false; });

It would be a complicated way of saying something simple, though.

Felix Ungman
how this will be possible have you tried ?
Pranay Rana
Yes, at least it works with linq-to-objects.
Felix Ungman
Which is equal to: list.Where(item => Foo(item));
Mel Gerats
A: 

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.

Ricardo Deano