A better Dictionary/Hashtable. One that allows multiple entries per key.

Ever need the speed of a dictionary or hashtable, but also want to store more than one item with the same key? i.e. Maybe you have lists of items that need to be indexed against certain keys.

Maybe, Orders keyed by UserId. Well, enter the easy to use MultiDictionary. A class I put together to make it much easier to accomplish the goal. Speed and usability in one easy to use package.

[csharp]
public class MultiDictionary<K, V>
{
private Dictionary<K, List<V>> _dict = new Dictionary<K, List<V>>();

public void Add(K key, V val)
{
List<V> values;
if (!_dict.TryGetValue(key, out values))
{
values = new List<V>();
_dict.Add(key, values);
}
values.Add(val);
}

public bool TryGetValue(K key, out List<V> values)
{
return _dict.TryGetValue(key, out values);
}

public List<V> this[K key]
{
get
{
if( _dict.ContainsKey(key) )
return _dict[key];

return new List<V>();
}
set
{
_dict[key] = value;
}
}

public bool ContainsKey(K key)
{
return _dict.ContainsKey(key);
}

public IEnumerable<K> Keys
{
get { return _dict.Keys; }
}

public IEnumerable<List<V>> Values
{
get { return _dict.Values; }
}
}

public static class Extensions
{
public static MultiDictionary<TKey, TSource> ToMultiDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
MultiDictionary<TKey, TSource> md = new MultiDictionary<TKey, TSource>();
foreach (var item in source)
{
md.Add(keySelector(item), item);
}
return md;
}

}
[/csharp]
 

 

No more key not found exceptions either. If I can’t find the key, you get back an empty collection. You can still use the ContainsKey to determine if the item is absent. This just makes it so much easier to populate your entity objects with empty collections, instead of all the null checking.

Use just like a normal Dictionary, just expect a collection to be returned every time instead of one item.

Happy coding!
 

Leave a Reply

Your email address will not be published. Required fields are marked *