开发者

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

开发者 https://www.devze.com 2023-02-13 15:21 出处:网络
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/deri

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?


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.


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.


I suspect it's because the IDictionary'2 interface came out long before ILookup'2 did. Going back and modifying is unnecessary. Concrete implementations can use ILookup'2. I don't see what would be gained by modifying an interface people have been using for years.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号