Can I / should I enumerate over an IGrouping more than once?
Is this code correct / safe? Is it safe to iterate an IGrouping more than once?
Or should I rather do:
5 Replies
It will enumerate twice
Which might or might not be an issue in your case
You could potentially materialize it to a dictionary, if you want to materialize it once and continue acting on a grouped pattern afterwards?
you mean something like
?
For example, yeah
Assume that, inside the loop, I do not mutate
myList
or any of its contents?Oh, if you are looking into modifying the source it might be a different story
Although, no, let me correct myself - I think your variable naming threw me off
You are iterating the IGrouping, not the IEnumerable<IGrouping>
I misread that earlier
In this case it is fine
Iterating IGrouping will not re-enumerate the initial IEnumerable
But considering your question in that light - If you end up modifying myList while iterating the groupings, it will not be reflected right away
You'd have to re-materialize the IEnumerable