Reputation: 305
I want to create a dictionary of the following type,
var data = new Dictionary<string, Dictionary<string, Dictionary<string, int>>>();
when I try to add value to the dictionary in the following way, I get a KeyNotFound Exception.
data[key1][key2][key3]= 3;
What am I doing wrong here? I assume if a key is not found in a dictionary, it is automatically added to it.
otherwise Is there any way to add keys at runtime?
I expect output of following type:
[male,[animal,[legs,4]
[eyes,2]]
[human,[hands,2]
[ears,2]]
[female,[animal,[nose,1]
[eyes,2]]
[bird,[wings,2]
[legs,2]]
Upvotes: 6
Views: 4245
Reputation: 47038
Depending in your key distribution and the number of entries it might be easier to use a Tuple<string, string, string>
as key:
var data = new Dictionary<Tuple<string, string, string>, int>();
data[Tuple.Create("key1", "key2", "key3")] = 1;
var itemFromDictionary = data[Tuple.Create("key1", "key2", "key3")];
Upvotes: 3
Reputation: 1135
You are trying to assign only the inner level value. You must assign to all levels.
Try this:
data["male"] = new[] {
{"animal", new[] {
{"legs",4},
{"eyes", 2}
},
{"human", new[] {
{"hands", 2}
}
};
I don't have a compiler here, so, I'm not sure it'll work.
Upvotes: 0
Reputation: 1704
you declare only 1 level dictionary, when you need to declare every level:
var data = new Dictionary<string, new Dictionary<string, new Dictionary<string, int>>>();
Hope this will help you.
Upvotes: 0
Reputation: 164291
The problem here is that you are only trying to assign to the innermost dictionary. But the two outer levels does not exist.
You need to be explicit about each level:
if (!data.ContainsKey(key1))
data[key1] = new Dictionary<string, Dictionary<string, int>();
... and so on. It can be a bit cumbersome to write, so if you need it a lot, I suggest you create an extension method on dictionary that lets you do this easily.
If you assign to a key in a dictionary, that entry is created. But if you read from a key in a dictionary, and that key does not exist, you get an exception.
Upvotes: 7