Search code examples
c#linqgroup-bylinq-to-objectsilookup

Does .GroupBy() guarantee order in its groupings?


Say I have an (ordered) sequence of animals:

Eagle
Elephant
Tarantula
Terrapin
Tiger

and I group by first letter:

Animals.GroupBy(animal => animal.First())

will the elements of the IGroupings in the resulting sequence be in the same order as the input sequence?


Solution

  • Yes, they will be: GroupBy (MSDN).

    The IGrouping<TKey, TElement> objects are yielded in an order based on the order of the elements in source that produced the first key of each IGrouping<TKey, TElement>. Elements in a grouping are yielded in the order they appear in source.