Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 777
richard Avatar asked Mar 02 '11 22:03

richard


People also ask

Can key-value pair have duplicate keys?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

What is a collection of key-value pairs?

A key-value database is a type of nonrelational database that uses a simple key-value method to store data. A key-value database stores data as a collection of key-value pairs in which a key serves as a unique identifier. Both keys and values can be anything, ranging from simple objects to complex compound objects.

Which of the collection uses key-value pair in Python?

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair.

What is a key-value pair example?

A key-value pair consists of two related data elements: A key, which is a constant that defines the data set (e.g., gender, color, price), and a value, which is a variable that belongs to the set (e.g., male/female, green, 100). Fully formed, a key-value pair could look like these: gender = male. color = green.


2 Answers

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.

like image 89
Ondrej Tucny Avatar answered Nov 06 '22 02:11

Ondrej Tucny


In .NET 3.5 and above, that is ILookup<TKey,TValue>. Unfortunately the only provided implementation is the immutable Lookup<TKey,TValue>, however it is easy to re-implement. An EditableLookup<TKey,TValue> is included in MiscUtil.

With an ILookup<TKey,TValue>, the TKey indexer returns an IEnumerable<TValue> (even if there were no matches for that key), so typical usage is:

foreach(var value in lookup[key])
    DoSomethingWith(value);
like image 35
Marc Gravell Avatar answered Nov 06 '22 04:11

Marc Gravell