Sort list while in a loop using groupby

I have a loop with linq like this:

foreach (var group in part.Profiles.Skip(ixstart).
             GroupBy(b => new { b.Number, b.X }).
             OrderBy(g => g.Key.Number).ThenBy(g => g.Key.X))
{
     // .... code
}

Is it safe to somewhere in the ... code sort the list part.Profiles.Sort()?
I do not get exceptions.

Jon Skeet
people
quotationmark

I suspect it turns out to be safe because GroupBy doesn't stream results - it consumes all of the input before it returns any values. (It's lazy in that it doesn't do any work until you ask it for its first element, but then it consumes all of the input.)

However, I would definitely not rely on that. It's going to ring alarm bells for many readers, and a seemingly-innocent change could mess everything up. I'd also say it's a confusing thing to do at all, sorting a collection within a loop that's iterating over that collection. Options:

  • Sort beforehand
  • Sort afterwards
  • Materialize the collection you're iterating over so it's independent of the original collection (e.g. by calling ToList() and using the result)

people

See more on this question at Stackoverflow