You can use the underlying iterators without creating the unnecessary garbage - essentially, you write what you would have liked the compiler to generate for you. The basic pattern is:
var enumerator = collection.GetEnumerator();
while (enumerator.MoveNext()) {
var element = enumerator.Current;
// loop body goes here
}
It is more complex though if the enumerator type is disposable, as you need to dispose of it appropriately, even if exceptions occur in your loop body. There are more details [here][1].
I think in modern parlance you can handle the exceptions more tidily than the linked page does, like this:
using (var enumerator = collection.GetEnumerator())
{
while (enumerator.MoveNext()) {
var element = enumerator.Current;
// loop body goes here
}
}
In practice though I would guess that any enumerator which requires disposal is going to create garbage anyway, and so you might as well just use the "foreach" in that case.
[1]: http://msdn.microsoft.com/en-us/library/aa664754(v=vs.71).aspx
↧