在字典内部的字典中添加键值对
Adding a key value pair in a dictionary inside a 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 有一个字典映射 string.Now 我想单独添加值到 insideDict。
我试过了
dict["blah"].Add();
我哪里错了?
Dictionary<string, Dictionary<string,TValue>> dic = new Dictionary<string, Dictionary<string,TValue>>();
用您的值类型替换 TValue。
你的意思是这样的吗?
var collection = new Dictionary<string, Dictionary<string, int>>();
collection.Add("some key", new Dictionary<string, int>());
collection["some key"].Add("inner key", 0);
如下所示
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("1", new Dictionary<string, int>());
(OR) 如果你已经定义了内部字典那么
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
。您应该将外部字典声明为强类型。
dict.Add("blah",insideDict); //forgot casting here
我有一个字典
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 有一个字典映射 string.Now 我想单独添加值到 insideDict。 我试过了
dict["blah"].Add();
我哪里错了?
Dictionary<string, Dictionary<string,TValue>> dic = new Dictionary<string, Dictionary<string,TValue>>();
用您的值类型替换 TValue。
你的意思是这样的吗?
var collection = new Dictionary<string, Dictionary<string, int>>();
collection.Add("some key", new Dictionary<string, int>());
collection["some key"].Add("inner key", 0);
如下所示
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("1", new Dictionary<string, int>());
(OR) 如果你已经定义了内部字典那么
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
。您应该将外部字典声明为强类型。
dict.Add("blah",insideDict); //forgot casting here