Can I / should I enumerate over an IGrouping more than once?

var groupings = myList.GroupBy(listElement => listElement.Key);
foreach(var groupoing in groupings)
{
foreach(var elt in grouping)
DoSomething(elt);
foreach(var elt2 in grouping)
DoSomethingElse(elt2);
}
var groupings = myList.GroupBy(listElement => listElement.Key);
foreach(var groupoing in groupings)
{
foreach(var elt in grouping)
DoSomething(elt);
foreach(var elt2 in grouping)
DoSomethingElse(elt2);
}
Is this code correct / safe? Is it safe to iterate an IGrouping more than once? Or should I rather do:
var groupings = myList.GroupBy(listElement => listElement.Key);
foreach(var grouping in groupings)
{
var groupingList = grouping.ToList();
foreach(var elt in groupingList)
DoSomething(elt);
foreach(var elt2 in groupoingList)
DoSomethingElse(elt2);
}
var groupings = myList.GroupBy(listElement => listElement.Key);
foreach(var grouping in groupings)
{
var groupingList = grouping.ToList();
foreach(var elt in groupingList)
DoSomething(elt);
foreach(var elt2 in groupoingList)
DoSomethingElse(elt2);
}
5 Replies
Sossenbinder
Sossenbinder2w ago
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?
YetAnohterOne
YetAnohterOneOP2w ago
you mean something like
var groupings = myList.GroupBy(listElement => listElement.Key);
var groupingsSafe = groupings.ToDictionary(g => g.Key, g => g.ToList());
foreach(var groupoing in groupingsSafe)
{
...
}
var groupings = myList.GroupBy(listElement => listElement.Key);
var groupingsSafe = groupings.ToDictionary(g => g.Key, g => g.ToList());
foreach(var groupoing in groupingsSafe)
{
...
}
?
Sossenbinder
Sossenbinder2w ago
For example, yeah
YetAnohterOne
YetAnohterOneOP2w ago
Assume that, inside the loop, I do not mutate myList or any of its contents?
Sossenbinder
Sossenbinder2w ago
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

Did you find this page helpful?