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.
Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>() { {"tab1", MyList } }; List <string> MyList = new List<string>() { "1" };
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.
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.
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 −
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" } }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With