initializing and assigning values to a dictionary in C#

In C#, you can initialize and assign a dictionary by using the following method:

// 方法1:使用字典初始化器
Dictionary<string, int> diinitializingassigning value

In C#, you can initialize and assign a dictionary by using the following method:

// 方法1:使用字典初始化器
Dictionary<string, int> dict1 = new Dictionary<string, int>

initializing

ct1 = new Dictionary<string, int>
{
    { "key1", 1 },
    { "key2", 2 },
    { "key3", 3 }
};

// 方法2:使用Add方法逐个添加键值对
Dictionary<string, int> dict2 = new Dictionary<string, int>();
dict2.Add("key1", 1);
dict2.Add("key2", 2);
dict2.Add("key3", 3);

// 方法3:使用键值对数组初始化字典
var keyValuePairs = new[]
{
    new KeyValuePair<string, int>("key1", 1),
    new KeyValuePair<string, int>("key2", 2),
    new KeyValuePair<string, int>("key3", 3)
};
Dictionary<string, int> dict3 = new Dictionary<string, int>(keyValuePairs);

These methods can all be used to initialize and assign values to a dictionary, choose the suitable method based on the actual scenario and personal preference.

 

More tutorials

How to retrieve a value from a C# dictionary using a key?(Opens in a new browser tab)

How to add elements to a C# dictionary(Opens in a new browser tab)

What is the method of initializing constructor in C++ using an initialization list?(Opens in a new browser tab)

How can I include new entries in a Python dictionary?(Opens in a new browser tab)

How is WinForms implemented in C#?(Opens in a new browser tab)

Leave a Reply 0

Your email address will not be published. Required fields are marked *