I need a Dictionary like object that can store multiple entries with the same key. Is this avaliable as a standard collection, or do I need to roll my own?
To clarify, I want to be able to do something like this:
var dict = new Dictionary<int, String>(); dict.Add(1, "first"); dict.Add(1, "second"); foreach(string x in dict[1]) { Console.WriteLine(x); }
Output:
first second
Answer. No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored.
In Dictionary, the key cannot be null, but value can be. In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception. In Dictionary, you can only store same types of elements.
Python dictionary doesn't allow key to be repeated.
In .NET 3.5 you can use a Lookup instead of a Dictionary.
var items = new List<KeyValuePair<int, String>>(); items.Add(new KeyValuePair<int, String>(1, "first")); items.Add(new KeyValuePair<int, String>(1, "second")); var lookup = items.ToLookup(kvp => kvp.Key, kvp => kvp.Value); foreach (string x in lookup[1]) { Console.WriteLine(x); }
The Lookup
class is immutable. If you want a mutable version you can use EditableLookup
from MiscUtil.
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