3

タプルをパラメーターとして Dictionary を使用しています。

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. 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));
于 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 に答える