3

我正在使用带有元组的字典作为参数。

Dictionary<string, List<Tuple<string, int>>> dict_Info_A = 
new Dictionary<string,List<Tuple<string,int>>>();

我无法初始化它,编译错误即将到来。请提出一些初始化它的方法。

提前致谢!

4

3 回答 3

3

这就是你如何使用集合初始化器来初始化你的字典:

Dictionary<string, List<Tuple<string, int>>> dict_Info_A = new Dictionary<string, List<Tuple<string, int>>>
{
    { "a", new List<Tuple<string, int>> { new Tuple<string, int>("1", 1) } } 
    { "b", new List<Tuple<string, int>> { new Tuple<string, int>("2", 2) } } 
};
于 2012-12-03T06:09:56.160 回答
1

我想你应该先决定,你需要什么字典

  1. 要么映射stringList<Tuple<string,int>>
  2. 或映射stringTuple<string,int>

有了这行代码

dict_Info_A.Add("A", new Tuple<string,int>("hello", 1));

你正在尝试使用Dictionary<string, Tuple<string, int>>

这样的字典应该像这样初始化:

var dict_Info_A = new Dictionary<string, Tuple<string, int>>();

这是您在原始问题中显示的字典:

使用var关键字初始化字典:

//you can also omit explicit dictionary declaration and use var instead
var dict_Info_A = new Dictionary<string, List<Tuple<string, int>>>();

初始化字典的一个元素:

dict_Info_A["0"] = new List<Tuple<string, int>>();

将元素添加到字典中的列表:

dict_Info_A["0"].Add(new Tuple<string, int>("asd", 1));
于 2012-12-03T06:06:32.360 回答
0

您不能使用(评论):

dict_Info_A.Add("A", new Tuple<string,int>("hello", 1));

因为字典想要一个list作为值。您可以执行以下操作:

List<Tuple<string,int>> list... // todo...
     // for example: new List<Tuple<string, int>> { Tuple.Create("hello", 1) };
dict_Info_A.Add("A", list);

如果您需要每个键多个值,并且想要附加到此列表,那么可能:

List<Tuple<string,int>> list;
string key = "A";
if(!dict_Info_A.TryGetValue(key, out list)) {
    list = new List<Tuple<string,int>>();
    dict_Info_A.Add(key, list);
}
list.Add(Tuple.Create("hello", 1));
于 2012-12-03T06:10:36.833 回答