Multivalue Dictionary in C#

Microsoft BCL team has released a new collection type called MultiValueDictionary which is now available in NuGet repository as a Microsoft.Experimental.Collections package. You can install this NuGet package through Package Manager Console using below command.

PM> Install-Package Microsoft.Experimental.Collections -Pre

We have already a collection type called Dictionary<TKey, TValue> to store data in the form of Key, Value pair. nice !!!.  But I have a requirement to store multiple Values for the same Key, something like below.

Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(1, “Item 1”);
dictionary.Add(1, “Item 2”);

The problem here is, Dictionary should not allow you to add the same Key multiple times. So I have to write something like below.

Dictionary<int, List<string>> dictionary = new Dictionary<int, List<string>>();
dictionary.Add(1, new List<string>(){“Item 1”, “Item 2”}); 

Fixed it :),

But the MultiValueDictionary  is more akin to a Dictionary<TKey, IReadOnlyCollection<TValue>> with a number of methods to enable the easy modification of the internal IReadOnlyCollection, also simplifies the above approach.

MultiValueDictionary<int, string> multiValueDictionary =new MultiValueDictionary<int, string>();
multiValueDictionary.Add(1, “Vimal”);
multiValueDictionary.Add(1, “CK”);
multiValueDictionary.Add(2, “vimkum”);

MultiValueDictionary allows you to add same key multiple times, but  it internally maintains a IReadOnlyCollection<TValue> to store values of the same key.

Console.WriteLine(“Items inside my Dictionary {0}”, multiValueDictionray.Count);

//Output : Total items inside my Dictionary : 2

foreach(var item in multiValueDictionary[1])

//Output : Vimal