问题描述
我一直无法阐明 ILookup
和 IGrouping
,并且很好奇我现在是否正确理解它.LINQ 通过生成 IGrouping
项的序列同时给我一个 ToLookup
扩展方法使问题复杂化.所以我感觉它们是一样的,直到我更仔细地观察.
I've been having trouble articulating the differences between ILookup<TKey, TVal>
and IGrouping<TKey, TVal>
, and am curious if I understand it correctly now. LINQ compounded the issue by producing sequences of IGrouping
items while also giving me a ToLookup
extension method. So it felt like they were the same until I looked more closely.
var q1 =
from n in N
group n by n.MyKey into g
select g;
// q1 is IEnumerable<IGrouping<TKey, TVal>>
相当于:
var q2 = N.GroupBy(n => n.MyKey, n => n);
// q2 is IEnumerable<IGrouping<TKey, TVal>>
看起来很像:
var q3 = N.ToLookup(n => n.MyKey, n => n);
// q3 is ILookup<TKey, TVal>
我在下面的类比中正确吗?
Am I correct in the following analogies?
- An
IGrouping
是单个组(即键控序列),类似于KeyValuePair
,其中值实际上是一个序列元素(而不是单个元素) - An
IEnumerable
是一个序列(类似于迭代 IDictionary
ILookup
更像是一个IDictionary
,其中的值实际上是一个元素序列
- An
IGrouping<TKey, TVal>
is a single group (i.e. a keyed sequence), analogous toKeyValuePair<TKey, TVal>
where the value is actually a sequence of elements (rather than a single element) - An
IEnumerable<IGrouping<TKey, TVal>>
is a sequence of those (similar to what you get when iterating over anIDictionary<TKey, TVal>
- An
ILookup<TKey, TVal>
is more like aIDictionary<TKey, TVal>
where the value is actually a sequence of elements
推荐答案
是的,所有这些都是正确的.
Yes, all of those are correct.
和 ILookup
还扩展了 IEnumerable
And ILookup<TKey, TValue>
also extends IEnumerable<IGrouping<TKey, TValue>>
so you can iterate over all the key/collection pairs as well as (or instead of) just looking up particular keys.
我基本上认为 ILookup
就像 IDictionary>
.
I basically think of ILookup<TKey,TValue>
as being like IDictionary<TKey, IEnumerable<TValue>>
.
请记住,ToLookup
是立即执行"操作(立即执行),而 GroupBy
是延迟的.碰巧的是,按照pull LINQ"的工作方式,当您开始从 GroupBy
的结果中提取 IGrouping
时,它无论如何都必须读取所有数据(因为您不能在中途切换组)而在其他实现中它可能能够产生流结果.(它在 Push LINQ 中实现;我希望 LINQ to Events 是相同的.)
Bear in mind that ToLookup
is a "do it now" operation (immediate execution) whereas a GroupBy
is deferred. As it happens, with the way that "pull LINQ" works, when you start pulling IGrouping
s from the result of a GroupBy
, it has to read all the data anyway (because you can't switch group midway through) whereas in other implementations it may be able to produce a streaming result. (It does in Push LINQ; I would expect LINQ to Events to be the same.)
这篇关于ILookup<TKey, TVal>对比 IGrouping<TKey, TVal>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!