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?
In LINQ, AsEnumerble() method is used to convert the specific type of given list to its IEnumerable() equivalent type.
Calling AsEnumerable( ) does not execute the query, enumerating it does. IQueryable is the interface that allows LINQ to SQL to perform its magic.
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.
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With