Anyone know of a good implementation of a MultiValueDictionary
? Basically, I want something that allows multiple values per key. I want to be able to do something like
dict.Add(key, val);
And if the key doesn't already exist, it will add it, if it does, it will just add another value to that key. I'm just going to iterate over it, so I don't really care about the other retrieval methods.
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
}