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

3
我正在使用以元组为参数的字典。
Dictionary<string, List<Tuple<string, int>>> dict_Info_A = 
new Dictionary<string,List<Tuple<string,int>>>();

我无法初始化它,出现编译错误。请建议一些初始化的方法。

提前感谢!


请问哪个异常出现了?请粘贴您的代码。 - Ravindra Bagale
1
停止撤销代码编辑,如果您不打算将其包含在代码块中,则代码不完全可见。 - Habib
2
定义上述字典时没有编译错误,您是如何使用它的,以及您遇到了什么错误。 - Habib
这是我正在使用的实现。 dict_Info_A.Add("A", new Tuple<string,int>("hello", 1)); - savalakh
@savalakh,您正在向字典值添加错误的类型。请尝试以下代码:dict_Info_A.Add("A", new List<Tuple<string, int>>() { new Tuple<string, int>("hello", 1) }); - Chris Li
3个回答

4
这是如何使用集合初始化器来初始化您的字典的方法:
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) } } 
};

1

我想你应该先决定需要哪种字典

  1. 要么将 string 映射到 List<Tuple<string,int>>
  2. 要么将 string 映射到 Tuple<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));

看起来我没有使用“var”关键字所需的引用/动态链接库。 - savalakh
@savalakh,你正在使用哪个版本的.Net进行编译?最终,你仍然使用显式声明。代码的所有其他部分保持不变。 - horgh

0

你不能使用(注释):

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

因为字典需要作为值的是列表。你可以这样做:

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));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接