Question initialize dictionary with keys/values

old1mike

New member
Joined
Jun 24, 2016
Messages
2
Programming Experience
Beginner
I am NOOB so please forgive is silly question. I have searched multiple websites for answers but could not find specific answer. This is the code I am trying to do:
Dictionary<int, List<int>> dictionary2 = new Dictionary<int, List<int>>()
            {
                [1] = { 1, 2, 3, 4 }
            };
foreach (var key in dictionary2.Keys)
                Console.WriteLine(key);
            Console.ReadKey();  //Pause

I am trying to figure out how to initialize a dictionary with a key and list. Using vs2015 up to date. When I put it in, VS does not highlight any thing is wrong, when I run debug am getting key not found error.
Any ideas as to what I am doing wrong would be appreciated.
Thanks in advance
 
I've never seen that syntax before but it appears to want to set an existing key. The correct syntax for what you're trying to do is this:
Dictionary<int, List<int>> dictionary2 = new Dictionary<int, List<int>>
{
    {1, new List<int> {1, 2, 3, 4}}
};
 
I just tried again and it seems that the syntax you were using was correct but you have to set the value with the correct type, i.e.:
Dictionary<int, List<int>> dictionary2 = new Dictionary<int, List<int>>
{
    [1] = new List<int> {1, 2, 3, 4}
};

foreach (var key in dictionary2.Keys)
    Console.WriteLine(key);

Console.ReadLine(); //Pause
I'm not sure why the compiler allowed you to write that code and it not execute but if you specify a List explicitly then the syntax works.
 
Thanks, it works. Was hoping to less typing but oh well. Am going to use this in building dictionarys and lists and put in DLLs for main program to access for decisions. Am thinking would be easier to update DLL to change decisions than putting in main body and having to update whole program. Not sure if this is 'proper' programming though. Still learning.
 
Back
Top Bottom