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 IGrouping
s in the resulting sequence be in the same order as the input sequence?
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.
Quote from the MSDN page for GroupBy:
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 eachIGrouping<TKey, TElement>
. Elements in a grouping are yielded in the order they appear in source.
So your example will result in:
Group 1
- Eagle
- Elephant
Group 2
- Tarantula
- Terrapin
- Tiger
Of course that only applies to the IEnumerable<T>
implementation. The IQueryable<T>
implementation has no such guarantee.
来源:https://stackoverflow.com/questions/12377891/does-groupby-guarantee-order-in-its-groupings