Does .GroupBy() guarantee order in its groupings?

百般思念 提交于 2019-11-29 13:26:24

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 each IGrouping<TKey, TElement>. Elements in a grouping are yielded in the order they appear in source.

So your example will result in:

  1. Group 1

    • Eagle
    • Elephant
  2. Group 2

    • Tarantula
    • Terrapin
    • Tiger

Of course that only applies to the IEnumerable<T> implementation. The IQueryable<T> implementation has no such guarantee.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!