I’ve been looking for a way to store and retrieve values on more than the single key that C#’s generic Dictionary class provides.
Searching around the web (and on SO itself) has shown me a couple options:
Tuple Based Dictionaries
.NET 4.0 makes it easy to support a generic Tuple<,> class. This means you can make a Dictionary out of any arbitrary Tuple, i.e.,
var myDict = new Dictionary<Tuple<Char, Int>, MyClass>();
Nested Dictionaries
I’ve learned you can also nest Dictionaries within Dictionaries, which makes accessing the stored result similar to accessing an N-Dimensional array. For instance:
Dictionary<int, Dictionary<int, Dictionary<Char, MyClass>>>
which could then be accsessed by: MyClass foo = MyData[8][3]['W'];
Delimited Concatenated Key Dictionaries
But while both work well for complex data and custom classes, I wonder if they’re always necessary. For primitive data, at least, it would seem that concatenating the keys with a delimiter is just as effective.
//keys are char + int
Dictionary<string, MyClass> myDict = New Dictionary<string, Myclass>();
String input = myChar + "|" + myInt
MyClass foo = myDict[input]
Are there any scenarios which make one of these methods superior to the other? Will they have similar performance times? Or should the focus be instead on which method provides the cleanest, easiest to maintain, code?
Thoughts?
Delimited Concatenated Key Dictionaries
There are at least three reasons why I would avoid this approach:
Nested Dictionaries
This solves the problem with the delimiter, but introduce some new problems:
Tuple Based Dictionaries
Of the approaches you posted, this is probably the best.
But you could take it one step further and create a named immutable
structfor your key. This will make your dictionary easier to use because the parts of the key can have useful names.