本文介绍了为什么 ToLookup 和 GroupBy 不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.ToLookup 返回一个 ILookup.ILookup 还实现了接口IEnumerable.

.ToLookup<TSource, TKey> returns an ILookup<TKey, TSource>. ILookup<TKey, TSource> also implements interface IEnumerable<IGrouping<TKey, TSource>>.

.GroupBy 返回一个 IEnumerable.

ILookup 具有方便的索引器属性,因此它可以以类似字典(或类似查找)的方式使用,而 GroupBy 则不能.没有索引器的 GroupBy 使用起来很痛苦;几乎可以引用返回对象的唯一方法是循环遍历它(或使用另一个 LINQ 扩展方法).换句话说,在 GroupBy 工作的任何情况下,ToLookup 也将工作.

ILookup has the handy indexer property, so it can be used in a dictionary-like (or lookup-like) manner, whereas GroupBy can't. GroupBy without the indexer is a pain to work with; pretty much the only way you can then reference the return object is by looping through it (or using another LINQ-extension method). In other words, any case that GroupBy works, ToLookup will work as well.

所有这些都让我产生了一个问题,为什么我会为 GroupBy 烦恼?为什么它应该存在?

All this leaves me with the question why would I ever bother with GroupBy? Why should it exist?

推荐答案

当您对一个代表包含十亿行的远程数据库表的对象调用 ToLookup 时会发生什么?

What happens when you call ToLookup on an object representing a remote database table with a billion rows in it?

十亿行通过网络发送,您可以在本地构建查找表.

The billion rows are sent over the wire, and you build the lookup table locally.

当你对这样的对象调用 GroupBy 时会发生什么?

What happens when you call GroupBy on such an object?

一个查询对象被构建;故事结束.

A query object is built; end of story.

当该查询对象被枚举时,表的分析就会在数据库服务器上完成,并且分组的结果一次按需发回几个.

When that query object is enumerated then the analysis of the table is done on the database server and the grouped results are sent back on demand a few at a time.

从逻辑上讲,它们是相同的东西,但每个的性能影响完全不同.调用 ToLookup 意味着我想要一个按组组织的整个事物的缓存.调用 GroupBy 的意思是我正在构建一个对象来表示‘如果我按组组织这些东西会是什么样子?’"

Logically they are the same thing but the performance implications of each are completely different. Calling ToLookup means I want a cache of the entire thing right now organized by group. Calling GroupBy means "I am building an object to represent the question 'what would these things look like if I organized them by group?'"

这篇关于为什么 ToLookup 和 GroupBy 不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 00:18