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.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
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.
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.
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.
Several options for you to consider:
Dictionary<TKey, List<TValue>>
— keep a list of values for each key, not preventing duplicate values for the same key (i.e. duplicate pairs);Dictionary<TKey, HashSet<TValue>>
— keep a set of value for each key, preventing duplicate values for the same key;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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With