Recently, I have been looking into implementing a multimap in C#. Basically, the multimap allows you to store different values with the same key. The NameValueCollection is something similar but not quite. As usual, looking around to see if anyone else has done this, I came across this article. However, the main gripe I have with this solution is the use of a List to store values.
What happens in the scenario where you have an entry with the same key and same value? Lots of duplicate values using the same key. Therefore, a HashSet should have been used here. The end result is the following code. I have also specified a generic key so it does not always need to be a String.
1 public class Multimap<K, V>
2 {
3 Dictionary<K, HashSet<V>> _dictionary = new Dictionary<K, HashSet<V>>();
4
5 public void Add(K key, V value)
6 {
7 HashSet<V> list;
8 if (_dictionary.TryGetValue(key, out list))
9 {
10 list.Add(value);
11 }
12 else
13 {
14 list = new HashSet<V> { value };
15 _dictionary[key] = list;
16 }
17 }
18
19 public void Add(K key, HashSet<V> values)
20 {
21 HashSet<V> list;
22 if (_dictionary.TryGetValue(key, out list))
23 {
24 list.UnionWith(values);
25 }
26 else
27 {
28 list = new HashSet<V>(values);
29 _dictionary[key] = list;
30 }
31 }
32
33 public IEnumerable<K> Keys
34 {
35 get
36 {
37 return _dictionary.Keys;
38 }
39 }
40
41 public HashSet<V> this[K key]
42 {
43 get
44 {
45 HashSet<V> list;
46 if (_dictionary.TryGetValue(key, out list))
47 {
48 return list;
49 }
50
51 return new HashSet<V>();
52 }
53 }
54 }