Stav Alfi
Stav Alfi

Reputation: 13923

I need confirmation about my understanding on IQueryable & IEnumerable

IQueryable From my understanding, In LINQ to SQL & Object , until I execute my query, I can add more expressions.

In this example, query1 and Query2 become final query when I try to execute Query2. Am I right? Or I am right if 'Numbers' was a DB?

    int[] Numbers= new int[] { 1, 2, 3, 4 };
    IQueryable<int> Query1 = from X in Numbers.AsQueryable()
                             where X > 1
                             select X;
    IQueryable<int> Query2 = from X in Query1
                             where X > 2
                             select X;
    //if I do this: Query2.Count() -> before it executes this, those two queries become one query (FinalQuery)?
    IQueryable<int> FinalQuery = from X in Query2
                                 where X > 2
                                 select X;

But, if I would use IEnumerable, Would it execute Query1 and get a IEnumerable. Then it would execute Query2 and get the final IEnumerable? ; Would it execute 2 queries?

Upvotes: 3

Views: 526

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273244

If I would use IEnumerable, Would it excute Query1 and get a IEnumerable. Then It would excute Query2 and get the final IEnumerable?

Yes. But they will be executed in tandem, each number X will 'flow' through both queries. That is called 'lazy evaluation' or 'deferred execution'.

Would it excute 2 querys ?

Yes. Overlapping in time.

[Using IQueryable] befor it excute this, those two querys become one query (FinalQuery)?

No.

Exactly the same thing will happen with IQueryable<> as with IEnumerable<>. There is no 'smart' component involved that will optimize where X > 1 away.

Upvotes: 1

Erix
Erix

Reputation: 7105

Neither IEnumerable nor IQueryable LINQ queries will execute until you try to actually use the result. They're both just classes containing extension methods of the same names. But they are both 'lazy' in that they return new queries, not actual results.

The general difference is that IEnumerable is using Funcs (essentially delegates) as the underlying storage of the query, whereas the IQueryable is using Expression Trees (so that the query can be 'translated' to SQL for example).

Upvotes: 1

Related Questions