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>>
Which is equivalent to:
var q2 = N.GroupBy(n => n.MyKey, n => n);
// q2 is IEnumerable<IGrouping<TKey, TVal>>
Which looks a lot like:
var q3 = N.ToLookup(n => n.MyKey, n => n);
// q3 is ILookup<TKey, TVal>
Am I correct in the following analogies?
- An
IGrouping<TKey, TVal>
is a single group (i.e. a keyed sequence), analogous to KeyValuePair<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 an IDictionary<TKey, TVal>
- An
ILookup<TKey, TVal>
is more like a IDictionary<TKey, TVal>
where the value is actually a sequence of elements
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…