Tag Archives: C#

Double Key Dictionary

Double Key Dictionary, or; how to make it really simple to use a dictionary with two keys.

In a matter of just weeks I found myself forced to temporarily store values with two unique identifying keys. As an example think about a customer in a web shop who has bought some books. Key number one would be the customer ID and then key number two would be the books ISBN number. The value stored could be the books name. Why you would want to do this I have no idea, but it’s an easy to understand example and it illustrates the problem I had so that everybody can understand it. Its just that I read values from, literally, thousands of Xml logs stored in a database… Anyway!

So what you could do is something like this:

Dictionary<string, Dictionary<string, string>> bookList = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> innerList = new…
innerList.Add(“11-22-33″, “Lord of the Rings”);
bookList.Add(“James”, innerList);

That works and would perhaps be good enough. But what happens if you want to compare two lists of books? And it’s not unthinkable that you might end up trying to add the same book, for the same person, more than once. How do you handle that? Lots of manual checks? More on my solution later on…

Even if I could make the problems outlined above go away (as in create little helper methods to sort them out) I just didn’t like the syntax. It felt just so wrong. What I wanted would be something like this:

DoubleKeyDictionary<string, string, string> bookListEx = new DoubleKeyDictionary<string, string, string>();
bookListEx.Add(“James”, “11-22-33″, “Lord of …”);

(Abbreviated for clarity)

So I implemented the DoubleKeyDictionary, as a two key generic dictionary. My implementation also includes IEnumerable<T>, IEquatable<T> and I added an index. All this enables me to use this syntax:

DoubleKeyDictionary<string, string, string> bookListEx = new DoubleKeyDictionary<string, string, string>();
bookListEx.Add(“James”, “11-22-33″, “Lord of the Rings”);

DoubleKeyDictionary<string, string, string> bookList = new DoubleKeyDictionary<string, string, string>();
bookList.Add(“James”, “10-20-30″, “Narnia”);

if (bookList.Equals(bookListEx))
    Console.WriteLine(“They are equal”);

foreach (DoubleKeyPairValue<string, string, string> books in bookListEx)
    Console.WriteLine(books.ToString());

Sorry about the bad formatting. Please download the actual code file [new window]. Please feel free to use the code if you like it. If not; tell me why!

12th of November edit: Code has finally been moved to Github! Please contribute!