簡體   English   中英

字典<string, List<Tuple<string, int> &gt;&gt; dict_Info_A = 新字典<string,List<Tuple<string,int> &gt;&gt;();

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

我正在使用帶有元組的 Dictionary 作為參數。

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

我無法初始化它,編譯錯誤即將到來。 請建議一些初始化它的方法。

提前致謝!

這是您使用集合初始值設定項來初始化您的字典的方式:

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

你不能使用(評論):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM