Igor Levashov
Igor Levashov

Reputation: 328

Multiple Where clauses in query using EF in C#

I have two IQueryable queries:

IQueryable<Ad> list1 = db.Ads.Where(x=>x.isModerated == true);
IQueryable<Ad> list2;

if(something == true)
{
    list2 = list1.Where(x=>x.TypeId == 2) 
    // is it going to be the same as query below?
    IQueryable<Ad> list1 = db.Ads.Where(x=>x.isModerated == true && x.TypeId == 2)   
}

and what if I would like to get a data using OR (||) operator is the same scenario.

And I believe it is going to be one db call until I want to iterate this query. Right?

Upvotes: 5

Views: 6463

Answers (3)

Chad
Chad

Reputation: 1562

is it going to be the same as query below?

Yes

and what if I would like to get a data using OR (||) operator is the same scenario.

Its going to be far less resource expensive to do it like:

IQueryable<Ad> list1 = db.Ads.Where(x=>x.isModerated);
IQueryable<Ad> list2;

if(something == true)
{
    list2 = list1.Where(x=>x.TypeId == 2) 
}
else 
{
    list2 = db.Ads.Where(x=>x.isModerated  || x.TypeId == 2)  
}

But if for some reason you do not want to do it that way you could do it:

list2 = list1.Union(db.Ads.Where(x=> x.TypeId == 2)) 

will give you the same result set

Upvotes: 7

Andrew Paes
Andrew Paes

Reputation: 2012

As I could notice, you do have a query with a where clause named list1, and if you do have something equal true, you would add another where clause so I would take a leaner, simpler approach I think.

IQueryable<Ad> list1 = db.Ads.Where(x => (x.isModerated == true) && (something != true || x.TypeId == 2));

List<Ad> fetchedAds = list1.ToList();

Upvotes: 1

Robert
Robert

Reputation: 106

list2 = list1.Where(x=>x.TypeId == 2) 
// is it going to be the same as query below?
IQueryable<Ad> list1 = db.Ads.Where(x=>x.isModerated == true && x.TypeId == 2)  

Yes - it will be the same.

Upvotes: 0

Related Questions