Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does converting IQueryable to IEnumerable execute the query again?

Tags:

c#

linq

In my query i need to return IEnumerable but i dont know if this action make the query to execute again?

var data = Repository<Person>.Find().AsEnumerable();

Find() returns IQueryable and because IQueryable inherits IEnumerable. I doubt if AsEnumerable make the repetitive execution.

I know that var data = Repository<Person>.Find().ToList() executes the query two times. One for Find() and second for Tolist()

like image 709
Adrakadabra Avatar asked Oct 31 '10 05:10

Adrakadabra


2 Answers

An IQueryable is an IEnumerable. There is no conversion, and therefore no work of any kind going on.

The work happens when you call GetEnumerator(), either explicitly or by invoking foreach on it.

Also, have you confirmed that Repository.Find().ToList() calls SQL twice? That doesn't sound right to me.

like image 99
Marcelo Cantos Avatar answered Oct 02 '22 10:10

Marcelo Cantos


AsEnumerable does not actually do anything except apply the as operator to your IQueryable. Accordingly, any future method you apply to your object will use the System.Linq.Enumerable set of extension methods as opposed to the System.Linq.Queryable methods.

It's all about deferred execution. Nothing ever gets executed against your queryable source (the database presumably) until you try to enumerate.

In other words:

var data=Repository.Find().AsEnumerable() 
/* The query is only actually performed AFTER here */  
.ToList();

If your code:

var data=Repository.Find().ToList();

executes the query two times, it's because you're doing something incorrect in your Find() method, which should definitely should not be the case.

var data = Respository.Find();

should execute the query ZERO times.

var result = data.ToList(); // THIS is what should execute the query.
like image 41
Jeff Avatar answered Oct 02 '22 12:10

Jeff