Skip to content

[Unity][C#] Use Dictionary to Store Key-Value Data

In Unity/C#, it is quite convenient to use Dictionary to store data, because the storage method of the dictionary is key-value correspondence, a key corresponds to a single value.

For example, it is easy to associate the item number with the item name.

The following record how to initialize a Dictionary data type variable, and add the data, get the data.


Dictionary Operation

Dictionary<TKey,TValue> Class


Initialization

Remember do not just use Dictionary<int, string> dict; to initialize, otherwise you will find that you cannot add any objects later.

Dictionary<int, string> dict = new Dictionary<int, string>();



Add the data

dict.Add(0, "bottle");
dict.Add(1, "letter");
dict.Add(2, "candy");



Get the data

Dictionary<int, string> dict = new Dictionary<int, string>();
            
dict.Add(0, "bottle");
dict.Add(1, "letter");
dict.Add(2, "candy");
            
Console.WriteLine(0);
Console.WriteLine(dict[0]);


Ouptut:

0
bottle


Get the number of data

Dictionary<int, string> dict = new Dictionary<int, string>();
            
dict.Add(0, "bottle");
dict.Add(1, "letter");
dict.Add(2, "candy");
            
Console.WriteLine(dict.Count);



Output:

3


Clear

Dictionary<int, string> dict = new Dictionary<int, string>();
            
dict.Add(0, "bottle");
dict.Add(1, "letter");
dict.Add(2, "candy");
dict.Clear();

Console.WriteLine(dict.Count);


Output:

0

References


Read More

Tags:

Leave a Reply