Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

11
  • 1
    Question about the ListCities() example. Why would it run only once ? I have had no problems foreaching over yield returns in the past. Commented Dec 4, 2012 at 11:07
  • 1
    He's not saying you would only get one result from the IEnumerable - he's saying that the SQL query (which is the expensive part of the method) would only execute once - this is a good thing. It would then read and yield all of the results from the query. Commented Dec 4, 2012 at 11:12
  • 9
    @Giorgio: While this question understandable, having a language's semantics pander to what a beginner might find confusing would not leave us with a very effective language. Commented Dec 4, 2012 at 16:49
  • 5
    LINQ isn't just semantic sugar. It provides delayed execution. And in the case of IQueryables (e.g. Entity Framework) allows for the query to be passed and composed until it's iterated (meaning that adding a where clause to a returned IQueryable will result in the SQL passed to the server upon iteration to include that where clause offloading the filtering onto the server). Commented Dec 4, 2012 at 17:51
  • 13
    Much as I like this answer, I think the examples are somewhat contrived. The summary at the end suggests that foreach is more efficient than for, when in actual fact the disparity is a result of deliberately broken code. The thoroughness of the answer redeems itself, but it's easy to see how a casual observer might come to the wrong conclusions. Commented Dec 6, 2012 at 23:39