Possible multiple enumeration of IEnumerable

Skip to end of metadata
Go to start of metadata

Consider the following code snippet:

Assuming that GetNames() returns an IEnumerable<string>, we are, effectively, doing extra work by enumerating this collection twice in the two foreach statements. If GetNames() results in a database query, you end up doing that query twice, while both times getting the same data.

This kind of problem can be easily fixed – simply force the enumeration at the point of variable initialization by converting the sequence to an array or a list, e.g.:

The rest of your code can stay the same, because both array and list types implement the IEnumerable interface.

Labels:
None
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.