タプルをパラメーターとして Dictionary を使用しています。
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) } }
};
どの辞書が必要か、最初に決めた方がいいと思います
string
へのマッピングList<Tuple<string,int>>
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));