Skip to content

[Unity][C#] 使用 Dictionary 儲存 key-value 型態的資料

在 Unity/C# 當中,使用字典 Dictionary 的資料型態來儲存資料是一件相當方便的事情,因為 Dictionary 儲存的方式為鍵值對應(key-value),一個 key 對應單一個 value。

比方說能很方便地將物品編號與物品名稱對應在一起。

以下就紀錄如何初始化一個 Dictionary 資料型態的變數,並完成添加資料、取得資料等基礎操作。


Dictionary 的操作

Dictionary<TKey,TValue> 類別


初始化

記得不要只使用 Dictionary<int, string> dict; 來初始化,否則會發現之後無法添加任何物件。

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



添加資料

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



取得資料

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


取得數量

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


清空

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