Adding a key value pair in a dictionary inside a dictionary

女生的网名这么多〃 提交于 2019-12-13 12:22:27

问题


I have a dictionary < string,object > which has a mapping of a string and a dictionary < string,int >. How do I add a key value pair in the inside dictionary < string ,int > ?

Dictionary <string,object> dict = new Dictionary <string,object>();
Dictionary <string,int> insideDict = new Dictionary <string,int>();
// ad some values in insideDict
dict.Add("blah",insideDict);

So now the dict has a dictionary mapped with a string.Now I want to separately add values to the insideDict. I tried

dict["blah"].Add();

Where am I going wrong?


回答1:


Something like below

        Dictionary<string, object> dict = new Dictionary<string, object>();
        dict.Add("1", new Dictionary<string, int>());

(OR) if you already have defined the inner dictionary then

        Dictionary<string, object> dict = new Dictionary<string, object>();
        Dictionary<string, int> innerdict = new Dictionary<string, int>();
        dict.Add("1", innerdict); // added to outer dictionary
        string key = "1";
        ((Dictionary<string, int>)dict[key]).Add("100", 100); // added to inner dictionary

Per your comment tried this but screwed up somewhere

You didn't got it cause of your below line where you forgot to cast the inner dictionary value to Dictionary<string, int> since your outer dictionary value is object. You should rather have your outer dictionary declared strongly typed.

dict.Add("blah",insideDict); //forgot casting here



回答2:


Do you mean something like this?

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

        collection.Add("some key", new Dictionary<string, int>());
        collection["some key"].Add("inner key", 0);



回答3:


Dictionary<string, Dictionary<string,TValue>> dic = new Dictionary<string, Dictionary<string,TValue>>();

Replace the TValue with your value type.



来源:https://stackoverflow.com/questions/38055708/adding-a-key-value-pair-in-a-dictionary-inside-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!