How can I initialize a System.Collections.Generic.List
of System.Collections.Generic.Dictionary
objects using Collection Initializers?
Asked
Active
Viewed 6,762 times
-1

maniak1982
- 707
- 2
- 7
- 23

Miguel Pragier
- 135
- 2
- 13
-
4When 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
-
1While 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 Answers
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
-
4
-
3@maniak1982: Why? Answering your own question is perfectly fine and encouraged on SO. – Heinzi Nov 12 '15 at 16:42
-
@M.kazemAkhgary Yes, that looks like a list of dictionaries to me! – Darren Gourley Nov 12 '15 at 16:47
-
It wasn't clear whether it was the answer or his existing code. It's not marked as the answer, after all. – maniak1982 Nov 12 '15 at 16:55
-
1@maniak1982, you cannot mark your own as an answer before (I believe) 24 hours. – Broots Waymb Nov 12 '15 at 17:26
-
Hi, all. The goal was, only to share some knowledge, indeed. If I had that question, I believe that others could have too. When the regular time restriction expire, I'll check my own answer. Unless some better answer appears :-) – Miguel Pragier Nov 13 '15 at 18:56
1
If you are using C# 6.0 you can use:
var myDict = new Dictionary<int, string>
{
[1] = "Pankaj",
[2] = "Pankaj",
[3] = "Pankaj"
};

Breno Queiroz
- 174
- 6