如何使用Collection Initializers初始化System.Collections.Generic.List
个System.Collections.Generic.Dictionary
个对象?
答案 0 :(得分:3)
List<Dictionary<string, object>> listaDeDicionarios = new List<Dictionary<string, object>>()
{
new Dictionary<string,object>()
{
{"chave1","valor um"},
{"chave2","dois"},
{"chave3",true}
},
new Dictionary<string,object>()
{
{"chave4",4},
{"chave5",DateTime.Now},
{"chave6",long.MaxValue},
{"chave7","..."}
},
new Dictionary<string,object>()
{
{"chave8","utf string áéí / &url"},
{"chave9",null},
{"chave10",String.Empty},
{"chave11",new List<string>(){"aaa","bbb","ccc","oh my god, it's a miracle!"}}
}
};
答案 1 :(得分:1)
如果您使用的是C#6.0,则可以使用:
var myDict = new Dictionary<int, string>
{
[1] = "Pankaj",
[2] = "Pankaj",
[3] = "Pankaj"
};