Just to add my $0.02 to the collection of solutions:
I had the same need back in 2011 and created a MultiDictionary
with a pedantically complete implementation of all the .NET interfaces. That includes enumerators that return a standard KeyValuePair<K, T>
and support for the IDictionary<K, T>.Values
property providing a collection of actual values (instead of an ICollection<ICollection<T>>
).
That way, it fits in neatly with the rest of the .NET collection classes. I also defined an IMultiDictionary<K, T>
interface to access operations that are particular to this kind of dictionary:
public interface IMultiDictionary<TKey, TValue> :
IDictionary<TKey, ICollection<TValue>>,
IDictionary,
ICollection<KeyValuePair<TKey, TValue>>,
IEnumerable<KeyValuePair<TKey, TValue>>,
IEnumerable {
/// <summary>Adds a value into the dictionary</summary>
/// <param name="key">Key the value will be stored under</param>
/// <param name="value">Value that will be stored under the key</param>
void Add(TKey key, TValue value);
/// <summary>Determines the number of values stored under a key</summary>
/// <param name="key">Key whose values will be counted</param>
/// <returns>The number of values stored under the specified key</returns>
int CountValues(TKey key);
/// <summary>
/// Removes the item with the specified key and value from the dictionary
/// </summary>
/// <param name="key">Key of the item that will be removed</param>
/// <param name="value">Value of the item that will be removed</param>
/// <returns>True if the item was found and removed</returns>
bool Remove(TKey key, TValue value);
/// <summary>Removes all items of a key from the dictionary</summary>
/// <param name="key">Key of the items that will be removed</param>
/// <returns>The number of items that have been removed</returns>
int RemoveKey(TKey key);
}
It can be compiled on anything from .NET 2.0 upwards and so far I've deployed it on the Xbox 360, Windows Phone 7, Linux and Unity 3D. There's also a complete unit test suite covering every single line of the code.
The code is licensed under the Common Public License (short: anything goes, but bug fixes to the library's code have to published) and can be found in my Subversion repository.