Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I misunderstanding LINQ to SQL .AsEnumerable()?

Consider this code:

var query = db.Table               .Where(t => SomeCondition(t))               .AsEnumerable();  int recordCount = query.Count(); int totalSomeNumber = query.Sum(); decimal average = query.Average(); 

Assume query takes a very long time to run. I need to get the record count, total SomeNumber's returned, and take an average at the end. I thought based on my reading that .AsEnumerable() would execute the query using LINQ-to-SQL, then use LINQ-to-Objects for the Count, Sum, and Average. Instead, when I do this in LINQPad, I see the same query is run three times. If I replace .AsEnumerable() with .ToList(), it only gets queried once.

Am I missing something about what AsEnumerable is/does?

like image 286
Ocelot20 Avatar asked Aug 02 '10 16:08

Ocelot20


People also ask

Why we use AsEnumerable in LINQ?

In LINQ, AsEnumerble() method is used to convert the specific type of given list to its IEnumerable() equivalent type.

Does AsEnumerable execute the query?

Calling AsEnumerable( ) does not execute the query, enumerating it does. IQueryable is the interface that allows LINQ to SQL to perform its magic.

Does LINQ query support immediate execution?

LINQ queries are always executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution. You can also force a query to execute immediately, which is useful for caching query results.

What is AsEnumerable in C#?

AsEnumerable() in C# To cast a specific type to its IEnumerable equivalent, use the AsEnumerable() method. It is an extension method. The following is our array − int[] arr = new int[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; Now, get the IEnumerable equivalent.


1 Answers

Calling AsEnumerable() does not execute the query, enumerating it does.

IQueryable is the interface that allows LINQ to SQL to perform its magic. IQueryable implements IEnumerable so when you call AsEnumerable(), you are changing the extension-methods being called from there on, ie from the IQueryable-methods to the IEnumerable-methods (ie changing from LINQ to SQL to LINQ to Objects in this particular case). But you are not executing the actual query, just changing how it is going to be executed in its entirety.

To force query execution, you must call ToList().

like image 57
Justin Niessner Avatar answered Oct 12 '22 13:10

Justin Niessner