How to initialize and assign values in a C# dictionary?
In C#, you can initialize and assign values to a dictionary using the following method:
- Using object initializers:
Dictionary<string, int> dict = new Dictionary<string, int>()
{
{"apple", 1},
{"banana", 2},
{"orange", 3}
};
- Add key-value pairs one by one using the Add method.
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("banana", 2);
dict.Add("orange", 3);
- Assigning values directly using an indexer.
Dictionary<string, int> dict = new Dictionary<string, int>();
dict["apple"] = 1;
dict["banana"] = 2;
dict["orange"] = 3;
All three methods can be used to initialize and assign values to a dictionary. Depending on the actual needs, one or more of these methods can be chosen for initialization.