LINQ To 对象 GroupBy 方法
LINQ To Objects GroupBy 方法如何工作?它是否会遍历整个集合中的每个键?有没有办法告诉 GroupBy 方法集合已排序?
How does LINQ To Objects GroupBy method work? Does it look throught the whole collection for each key? Is there any way to say to GroupBy method that collection is sorted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果做得明智,GroupBy 将在单次向前传递中发挥作用。基本的实现(不是他们的)类似于:
基本上按键分组,为每个唯一键创建一个包含值的列表。
您可以做一些事情,例如与最后看到的键进行比较(以帮助排序数据),但是......您需要进行分析才能知道它是否值得。
GroupBy, if done sensibly, would work in a single forwards only pass. A basic implementation (not theirs) would be something comparable to:
That basically groups by key, creating a list for each unique key, containing the values.
You could do things like compare to the last-seen key (to help with sorted data), but... you'd need to profile to know if it is worthwhile.
让我们看看重载
,因为它是最容易理解的。实际上,代码将执行如下操作:
枚举
source
对于源中的每个
element
,将元素映射到key = keySelector(element)
看看是否
key
位于由TKey
键控的字典中如果不是,请添加值为
List
的key
和第一项element
否则,获取与键关联的
List
并将element
添加到列表中现在您有一个字典映射
TKey
->TSource
并且可以轻松产生IGrouping
序列。因此,像
从这里开始,您可以轻松生成
IGrouping
序列。我不明白为什么你认为排序列表很重要。
Let's just look at the overload
as its the simplest to understand. Effectively the code will do something like this:
Enumerate through
source
For each
element
in source, map element tokey = keySelector(element)
See if
key
is in a dictionary keyed byTKey
if it is not, add the
key
with the value aList<TSource>
and first itemelement
else, get the
List<TSource>
associated to key and addelement
to the listNow you have a dictionary mapping
TKey
->TSource
and can easily produce a sequence ofIGrouping<TKey, TElement>
.So something like
From here you can easily yield a sequence of
IGrouping<TKey, TSource>
.I don't see why you think the list being sorted matters.
不会。GroupBy 的实现是 O(n),而不是 O(n^2)
No. The implementation of GroupBy is O(n), not O(n^2)