LINQ enumeration gotcha

Rick Strahl has posted about enumerating over LINQ results. Essentially, each item enumerated in a LINQ-to-SQL select fires off a new DB query. This means that modifying the result will not affect the resultset on the next enumeration (which probably sounds obvious, but is easy to code without noticing. Especially if you are working on a result and then databinding as in Rick’s example). It also means that repeated traversals will incur a repeated overhead, rather than repeating the work in-memory.

Good to watch out for. Rick suggests using ToList, ToArray, or ToDictionary methods if you want to grab a single, in-memory copy of the result (obviously being mindful of the result size :)).

Comments