Adding a key value pair in a dictionary inside a dictionary

我的梦境 提交于 2019-12-04 19:19:22

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

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);
Dictionary<string, Dictionary<string,TValue>> dic = new Dictionary<string, Dictionary<string,TValue>>();

Replace the TValue with your value type.

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