-1

How can I initialize a System.Collections.Generic.List of System.Collections.Generic.Dictionary objects using Collection Initializers?

maniak1982
  • 707
  • 2
  • 7
  • 23
Miguel Pragier
  • 135
  • 2
  • 13
  • 4
    When asking a question, it's always a good idea to show what you've tried and what went wrong. In this case, it's not clear whether you know how to use collection initializers to a) initialize a list; b) initialize a dictionary. If you know both of those, combining them is easy. If you don't know one of them, *that's* what your question should be about. In this case, it's not really clear why you would ask the question and self-answer... it's not a question which is likely to come up, IMO. – Jon Skeet Nov 12 '15 at 16:34
  • 1
    While it's fine to add your own question and answer, it *isn't* fine to just keep adding endless permutations of answered scenarios. The answer to "how to initialize a list of dictionaries" is to look at the questions for "how to initialize a list" and "how to initialize a dictionary". There's nothing special about a list of dictionaries in particular. – Luaan Nov 12 '15 at 16:46
  • Hi, Luaan. I understand that there's nothing special for you, probably used to c# semantics, but defnitely it's not the same. Dictionary is essentially different from List>. So, I strongly disagree of your moderation. – Miguel Pragier Nov 13 '15 at 18:50

2 Answers2

6
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!"}}
    }
};
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
Miguel Pragier
  • 135
  • 2
  • 13
1

If you are using C# 6.0 you can use:

var myDict = new Dictionary<int, string>
{
    [1] = "Pankaj",
    [2] = "Pankaj",
    [3] = "Pankaj"
};