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?
Calling
AsEnumerable() does not execute the query, enumerating it does.IQueryableis the interface that allowsLINQ to SQLto perform its magic.IQueryableimplementsIEnumerableso when you callAsEnumerable(), you are changing the extension-methods being called from there on, ie from theIQueryable-methods to theIEnumerable-methods (ie changing fromLINQ to SQLtoLINQ to Objectsin 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().