简体   繁体   English

.GroupBy()是否保证其分组中的顺序?

[英]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 IGrouping s in the resulting sequence be in the same order as the input sequence? 结果序列中IGrouping的元素是否与输入序列的顺序相同?

Yes, they will be: GroupBy (MSDN) . 是的,它们将是: 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>. 根据产生每个IGrouping <TKey,TElement>的第一个键的源中元素的顺序,按顺序产生IGrouping <TKey,TElement>对象。 Elements in a grouping are yielded in the order they appear in source. 分组中的元素按它们在源中出现的顺序产生。

Quote from the MSDN page for GroupBy: MSDN页面引用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> . 所述IGrouping<TKey, TElement>对象的顺序,得到基于所产生的每一个第一密钥在源中的元素的顺序上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 2组

    • Tarantula 塔兰图拉毒蛛
    • Terrapin 水龟
    • Tiger

Of course that only applies to the IEnumerable<T> implementation. 当然,这仅适用于IEnumerable<T>实现。 The IQueryable<T> implementation has no such guarantee. IQueryable<T>实现没有这样的保证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM