NGenerics overview - the HashList

NGenerics overview - the HashList

Something that I find a use for in almost every project I work on, is the HashList (also known as a MultiMap in the Java world) in NGenerics 1.2. A HashList is a multi-valued dictionary that uses a Dictionary<TKey, IList> under the covers. It still retains dictionary semantics but handles the creation and destruction of the key/list pairs itself.

For example, adding a couple of items to the HashList will have the following result:

var legsHashList = new HashList();
legsHashList.Add(4, "Cow");
legsHashList.Add(4, "Horse");
legsHashList.Add(2, "Chimpanzee");
legsHashList.Add(8, "Spider");
Key Values
4 Cow Horse
2 Chimpanzee  
8 Spider  

Removing the cow and the horse will result in removing the list (and the key) from the dictionary, affecting both the key count and the value count.  The HashList implements IEnumerable<KeyValuePair<TKey, IList<TValue»> so you can traverse items in grouped order. Sure beats the heck out of having all that list management code sitting in your code base.

Photo by Pankaj Patel on Unsplash


See also