Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

MultiKeyDictionary generic class.

4.00/5 (4 votes)
5 Jul 2011CPOL 16.1K  

Introduction


Dictionary<TKey, TValue> class allows only one object to serve as a key for its key/value element. But there are situations that require the key to consist of more than one entity.

The MultiKeyDictionary<TKey1, TKey2, TValue> class implements Dictionary<TKey, TValue>-like functionality, but unlike Dictionary<TKey, TValue> each key consists of two parts.


Background


MultiKeyDictionary<TKey1, TKey2, TValue> class is one of several classes implemented in my POSOlSoft.MultiKeyDictionary free .NET component.

Using the Code


Members of the MultiKeyDictionary<TKey1, TKey2, TValue> class are described in the XML documentation contained in the source code.

Usage of the MultiKeyDictionary<TKey1, TKey2, TValue> class is very similar to the Dictionary<TKey, TValue> class usage and is quite straightforward:


MultiKeyDictionary<string, string, int> mkd = new MultiKeyDictionary<string, string, int>();
mkd.Add( "one", "two", 3 );
mkd[ "four", "five" ] = 6;
Console.WriteLine( mkd.Count );
Console.WriteLine( mkd[ "one", "two" ] );
foreach ( var e in mkd )
{
  Console.WriteLine( e );
}
etc...

Points of Interest


Functionality implemented by the MultiKeyDictionary<TKey1, TKey2, TValue> class is similar to functionality of the Dictionary<Tuple<TKey1, TKey2>, TValue> class. But MultiKeyDictionary<TKey1, TKey2, TValue> class is much faster.


Performance comparison of MultiKeyDictionary<TKey1, TKey2, TValue> class against Dictionary<Tuple<TKey1, TKey2>, TValue> class may be found here: http://www.posolsoft.com/products/MKDTupleDictionaryTest.htm.


History


4 July 2011 - first version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)