Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize Dictionary<string, List<string>>

Tags:

c#

dictionary

I would like to know how do I declare/initialize a dictionary ? The below one gives error.

Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>()
{
  {"tab1", MyList }
};

List <string> MyList = new List<string>() { "1" };

The error is: A field initializer cannot reference the non-static field, method, or property MyList. It is not List declaration coming in front or later after dictionary.

like image 819
GManika Avatar asked Jan 23 '13 04:01

GManika


People also ask

How declare dictionary of List in C#?

Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>() { {"tab1", MyList } }; List <string> MyList = new List<string>() { "1" };

How do you initialize a dictionary?

Initialization. Dictionaries are also initialized using the curly braces {} , and the key-value pairs are declared using the key:value syntax. You can also initialize an empty dictionary by using the in-built dict function. Empty dictionaries can also be initialized by simply using empty curly braces.

What is the use of dictionary in C#?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.

What is list and dictionary in C#?

Dictionary is a generic type and returns an error if you try to find a key which is not there. List collection is a generic class and can store any data types to create a list. A list is a group of items −


1 Answers

Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>()
{
    {"tab1", new List<string> { "1" } },
    {"tab2", new List<string> { "1","2","3" } },
    {"tab3", new List<string> { "one","two" } }
};
like image 141
benkevich Avatar answered Sep 23 '22 19:09

benkevich