在字典内的字典中添加键值对 [英] Adding a key value pair in a dictionary inside a dictionary
问题描述
我有字典< string,object>,具有字符串和字典的映射< string,int>.如何在内部字典<中添加键值对字符串,int>?
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);
所以dict现在有一个字典映射了一个字符串,现在我想将值分别添加到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();
我要去哪里错了?
推荐答案
类似下面的内容
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("1", new Dictionary<string, int>());
(OR)(如果您已经定义了内部字典)
(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
根据您的评论尝试了此操作,但将其固定在某个地方
您没有得到它的原因是由于您的下一行忘记了将内部字典值强制转换为Dictionary<string, int>
,因为您的外部字典值是object
.您应该将您的外部字典声明为强类型.
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
这篇关于在字典内的字典中添加键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!