Search code examples
.netdictionarygeneric-collections

Is there a generic collection with a key/value pair where key can occur more than once?


I want to use a generic collection like Dictionary, but Dictionary requires that every key be unique. I have multiple values for the same "key", so I need a generic collection that will allow for that.

I realize that this makes the key no longer really a key, but I don't know what else to call it.


Solution

  • Several options for you to consider:

    • use a Dictionary<TKey, List<TValue>> — keep a list of values for each key, not preventing duplicate values for the same key (i.e. duplicate pairs);
    • use a Dictionary<TKey, HashSet<TValue>> — keep a set of value for each key, preventing duplicate values for the same key;
    • use a List<KeyValuePair<TKey, TValue>> — keep a list of pair, not preventing duplicate values for the same key.

    Note that in the latter case KeyValuePair is a struct, not a class, hence that implies a bit different handling.

    The right option depends on your actual use case.