5

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?

2

3 Answers 3

7

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

0
1

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();
0
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.

1
  • And yes it will be one db call unless you enumerate through this.
    – Robert
    Commented Jul 18, 2018 at 20:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.