Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't/couldn't IDictionary<TKey,TValue> implement ILookup<TKey,TValue>?

Tags:

c#

dictionary

I suppose this doesn't really matter, I'm just curious.

If the difference between dictionary and lookup is one is one-to-one and the other one-to-many, wouldn't dictionary by a more specific/derived version of the other?

A lookup is a collection of key/value pairs where the key can be repeated. A dictionary is a collection of key/value pairs where the key cannot be repeated.

Why couldn't IDictionary implement ILookup?

like image 481
Josh Avatar asked May 22 '26 18:05

Josh


2 Answers

I suspect this is mainly because the intention is different.

ILookup<T,U> is designed specifically to work with a collection of values. IDictionary<T,U> is intended to work with a single value (that could, of course, be a collection).

While you could, of course, have IDictionary<T,U> implementations implement this via returning an IEnumerable<U> with a single value, this would be confusing, especially if your "U" is a collection itself (ie: List<int>). In that case, would ILookup<T,U>.Item return an IEnumerable<List<int>>, or should it do some type of check for an IEnumerable<T> value type, and then "flatten" it? Either way, it'd look confusing, and add questionable value.

like image 141
Reed Copsey Avatar answered May 25 '26 06:05

Reed Copsey


Interfaces IDictionary<T,U> and ILookup<T,U> both inherit IEnumerable. If an IDictionary<T,U> is cast to IEnumerable and GetEnumerator() is called on it, the resulting enumerator should return instances of KeyValuePair<T,U>. If an ILookup<T,U> is cast to IEnumerable and GetEnumerator() is called upon it, the resulting enumerator should return instances of IGrouping<T,U>. If the KeyValuePair<T,U> struct were modified to implement IGrouping<T,U> that might be workable, but hardly clean.

like image 39
supercat Avatar answered May 25 '26 06:05

supercat