Search code examples
c#linqentity-frameworklinq-to-entities

Is ToList required when using foreach with LINQ to Entities


I have a performance question regarding how LINQ performs with a foreach over an queryable entities from Entity Framework.

Is it better (and faster) to do either

foreach(var thing in myentities.GetThemAll())

or

foreach(var thing in myentities.GetThemAll().ToList())

Will the first example actually result in myentities.GetThemAll().Count() (+1 ?) trips to the database each collecting one row?


Solution

  • It is better, if you have only to iterate through your elements to not call ToList(). This is because when we call it, an immediate execution of the corresponding query is triggered and one in memory collection will be created.

    If you don't call ToList you will avoid the creation of the in memory collection that will hold the results of your query.

    Either you follow the first way, either the second, you will make one round trip to the database.