简体   繁体   中英

Why doesn't IGrouping inherit IEnumerable<KeyValuePair> like IDictionary?

IGrouping:

public interface IGrouping<out TKey, out TElement> : IEnumerable<TElement>, 
IEnumerable

IDictionary:

public interface IDictionary<TKey, TValue> : ICollection<KeyValuePair<TKey, TValue>>, 
IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable

So, IDictionary implements IEnumerable<KeyValuePair<TKey, TValue>> while IGrouping implements IEnumerable<TElement> . If the elements of IGrouping contain keys, why does the interface not also use KeyValuePair ? It also seems like methods implemented in IDictionary that would be useful for IGrouping such as IDictionary.ContainsKey are unavailable in IGrouping , meaning any attempt to find a key on a group (in O(1) time) would look something like:

List<int> myList = new List<int>{ 1, 2, 3, 1};
var grp = myList.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
if (grp.ContainsKey(someValue)){...}

Am I just using IGrouping wrong? What am I missing?

To find if a particular IGrouping<TKey, TValue> contains a particular TKey , just check its Key property directly. No need for a loop.

GroupBy doesn't return IGrouping , it returns IEnumerable<IGrouping<...>> . That is, IGrouping represents the results for one single key value, and you get multiple such results. It cannot return Dictionary<TKey, TValue> , as GroupBy preserves key order, and Dictionary doesn't. No other pre-existing collection type is appropriate here.

Since you don't care about key order, and also don't care about the individual values for each key (since they're identical), you can store your results in a dictionary yourself, like you're doing now. You're doing the right thing.

If you don't need the counts, you can also use a HashSet<int> .

If you end up needing the individual values, you can also use ToLookup .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM