1

I've got a problem i need to create 2 dimensional table which will be indexed by string for example:

table["London","Cambridge"] = 120;

or jagged:

table["London"]["Cambridge"] = 120;

How to declare Collection or array that can handle this? I found solution but im not sure it is the best.

Dictionary<string, Dictionary<string, int>> test = new Dictionary<string, Dictionary<string, int>>();

But when i wanna create a new value i need to initialize new dictionary, so why i thing that solution is not the rightest:

table.Add("London", new Dictionary<string, int> {{"Cambridge",120}});

So how in the best way create 2 dimensional array indexed by string (mayby create new class that can handle this)?

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • Would a DataTable be appropriate here? Is the number of strings being used ever liable to change? – Paddy Nov 12 '10 at 16:35

1 Answers1

2

I wrote a MultiKey-dictionary once, lets see, here it is.

You can get or set an element by two keys like this dictionary["key1", "key2"].

Edit:
But I suppose with the Tuple type in .NET 4 you can use a Tuple as key instead of using nested dictionaries.

public class Dictionary<TKey1, TKey2, TValue> : Dictionary<Tuple<TKey1, TKey2>, TValue>
...
Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108