Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding to a Dictionary within a dictionary

I am not a particularly confident programmer yet but am getting there.

My problem is that I have a

    static Dictionary<string, Dictionary<string, List<string>>> testDictionary = ...

If the Dictionary doesn't contain the current key (string), I can easily add the key and another dictionary that has been populated, like so...

   testDictionary.Add(userAgentResult, allowDisallowDictionary);

That works fine, my problem comes when I am trying to add the inner dictionary if the userAgentResult Key already exists.

I was hoping to do it this way...

    testDictionary[userAgentResult].Add(allowDisallowDictionary);

but the .Add method wants two arguments, i.e. the string key and list value. So I went on to write this code...

    //this list as the dictionary requires a list
    List<string> testDictionaryList = new List<string>();
    //this method returns a string
    testDictionaryList.Add(regexForm(allowResult, url));
    //this will add the key and value to the inner dictionary, the value, and then     
    //add this value at the userAgentKey
    testDictionary[userAgentResult].Add(allowDisallowKey, testDictionaryList);

This also works, my problem is that this dictionary is added to numerous times, and when the inner dictionary already contains the key that is trying to be added, it obviously errors. So when

like image 963
Michael B Avatar asked Feb 08 '12 22:02

Michael B


3 Answers

I would probably simplify this by having one dictionary and joining the keys thus "simulating" a grouping.

 string key = userAgentResult + allowDisallowKey;

 static Dictionary<string, List<string> testDictionary = ...

 testDictionary[key] = list;

You simply need to manage one dictionary.

like image 195
Razor Avatar answered Sep 26 '22 01:09

Razor


In this case what you need to do is not adding an entry to the inner dictionary. You need to add the value to the key-value pair of the outer dictionary. Only this time the value happens to be yet another dictionary :)

testDictionary[userAgentResult] = allowDisallowDictionary;

like image 34
Sofian Hnaide Avatar answered Sep 25 '22 01:09

Sofian Hnaide


Maybe i don't get your problem. First make sure that dictionaries exist like so:

if (!testDictionary.ContainsKey(userAgentResult))
    testDictionary[userAgentResult] = new Dictionary<string, List<string>>();
if (!testDictionary[userAgentResult].ContainsKey(allowDisallowKey))
    testDictionary[userAgentResult][allowDisallowKey] = new List<string>();

Then you are free to add items like so:

testDictionary[userAgentResult][allowDisallowKey].Add("some value");
testDictionary[userAgentResult][allowDisallowKey].AddRange(someValueList);
like image 45
Nikola Radosavljević Avatar answered Sep 23 '22 01:09

Nikola Radosavljević