tags:

views:

1255

answers:

3

Does anyone know if there is a way I can insert values into a C# Dictionary when I create it? I can, but don't want to, do dict.Add(int, "string") for each item if there is something more efficient like:

Dictionary<int, string>(){(0, "string"),(1,"string2"),(2,"string3")};
+6  A: 

There's whole page about how to do that here:

http://msdn.microsoft.com/en-us/library/bb531208.aspx

Daniel Earwicker
Sorry, I used the wrong search terms on Google apparently. This link is great.
kd7iwp
This only works on .NET 3.5 compiler though... just keep that in mind.
Adrian Godong
@kd7iwp - no problem, part of the function of this site is so that alternative search terms can get routed to something useful.
Daniel Earwicker
+4  A: 
Dictionary<int, string> dictionary = new Dictionary<int, string> { 
   { 0, "string" }, 
   { 1, "string2" }, 
   { 2, "string3" } };
Timothy Carter
+1  A: 

You can instantiate a dictionary and add items into it like this:

var dictionary = new Dictionary<int, string>
    {
        {0, "string"},
        {1, "string2"},
        {2, "string3"}
    };
Joseph