如何初始化词典列表

时间:2015-11-12 16:32:34

标签: c# .net generics

如何使用Collection Initializers初始化System.Collections.Generic.ListSystem.Collections.Generic.Dictionary个对象?

2 个答案:

答案 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"
};