在字典中添加字典中的键值对
本文关键字:字典 键值对 添加 | 更新日期: 2023-09-27 17:52:11
我有一本字典<字符串,对象>,其具有字符串和字典的映射<字符串,int>。如何在内部字典中添加键值对<字符串,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添加值。我试过
dict["blah"].Add();
我哪里错了?
你的意思是这样的吗?
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>());
(或者(如果你已经定义了内部字典,那么
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, Dictionary<string,TValue>> dic = new Dictionary<string, Dictionary<string,TValue>>();
将TValue替换为您的值类型。