Multi value Dictionary
Microsoft just added an official prelease version of exactly what you're looking for (called a MultiValueDictionary
) available through NuGet here: https://www.nuget.org/packages/Microsoft.Experimental.Collections/
Info on usage and more details can be found through the official MSDN blog post here: http://blogs.msdn.com/b/dotnet/archive/2014/06/20/would-you-like-a-multidictionary.aspx
I'm the developer for this package, so let me know either here or on MSDN if you have any questions about performance or anything.
Hope that helps.
It doesn't exist, but you can build one pretty quickly from Dictionary and List:
class MultiDict<TKey, TValue> // no (collection) base class
{
private Dictionary<TKey, List<TValue>> _data = new Dictionary<TKey,List<TValue>>();
public void Add(TKey k, TValue v)
{
// can be a optimized a little with TryGetValue, this is for clarity
if (_data.ContainsKey(k))
_data[k].Add(v);
else
_data.Add(k, new List<TValue>() { v}) ;
}
// more members
}
You can easily make one from a dictionary of lists:
public class MultiValueDictionary<Key, Value> : Dictionary<Key, List<Value>> {
public void Add(Key key, Value value) {
List<Value> values;
if (!this.TryGetValue(key, out values)) {
values = new List<Value>();
this.Add(key, values);
}
values.Add(value);
}
}
You can always use a Tuple for your second generic parameter:
var dict = new Dictionary<string,Tuple<string,int,object>>();
dict.Add("key", new Tuple<string,int,object>("string1", 4, new Object()));
Or even , a generic List as a second generic parameter:
var dict = new Dictionary<string,List<myType>>();
That will allow you to bind multiple values to a single key.
For ease of use, you can create an extension method that will check for existence of a key and addition to the list.