iT邦幫忙

2024 iThome 鐵人賽

DAY 7
0
自我挑戰組

C# 由淺入深系列 第 7

Day7 Dictionary2

  • 分享至 

  • xImage
  •  

主要特點

  1. 鍵和值的對應:
    每個鍵都對應一個值。鍵用來唯一標識每個值。
    值可以是任何類型的數據,而鍵通常是可以用來比較的類型,如 int、string 或自定義的類型。
  2. 快速查找:
    Dictionary 使用哈希表來儲存鍵值對,這使得根據鍵快速查找對應的值成為可能。一般來說,查找操作的時間複雜度為 O(1),即常數時間。
  3. 不允許重複的鍵:
    在 Dictionary 中,鍵必須是唯一的。如果嘗試插入具有相同鍵的項目,舊的值將被新值覆蓋。
  4. 動態擴展:
    Dictionary 會根據需要自動擴展,以容納更多的鍵值對。這樣用戶不必擔心預先分配足夠的空間。
  5. 支持遍歷:
    可以遍歷 Dictionary 中的所有鍵值對,通常使用 foreach 迴圈來完成。
  6. 查詢和操作:
    提供了多種方法來查詢、添加、更新和移除鍵值對。例如,TryGetValue 用於安全地查找值,Remove 用於刪除鍵值對。

使用情境

Dictionary 非常適合用於需要快速查找、插入或更新數據的場景,比如:

  • 儲存用戶信息(例如,使用用戶ID作為鍵)。
  • 處理配置設定(例如,使用設定名稱作為鍵)。
  • 管理對象屬性(例如,使用屬性名稱作為鍵)。

例子

using System;

class Program
{
    static void Main(string[] args)
    {
        /*
        // 創建一個 Dictionary,鍵是 int,值是 string
        // 使用 KeyValuePair 的方式添加元素
        Dictionary<int, string> names = new Dictionary<int, string>
        {
            {1, "Aba"},    // 添加鍵值對 1 -> "Aba"
            {2, "Test"},   // 添加鍵值對 2 -> "Test"
            {3, "TEST"}    // 添加鍵值對 3 -> "TEST"
        };

        // for遍歷
        // 使用 ElementAt(i) 來取得第 i 個元素
        for (int i = 0; i < names.Count; i++)
        {
            // 透過 ElementAt(i) 方法來取得字典中的第 i 個 KeyValuePair
            KeyValuePair<int, string> pair = names.ElementAt(i);

            Console.WriteLine($"Key is {pair.Key} Value is {pair.Value}");
        }

        Console.WriteLine();

        // foreach遍歷
        foreach (KeyValuePair<int, string> pair in names)
        {
            Console.WriteLine($"Key is {pair.Key} Value is {pair.Value}");
        }
        */

        // 創建一個 Dictionary,鍵和值的類型都是 string
        // 初始包含兩個鍵值對:{"Math", "Aba"} 和 {"Science", "Test"}
        Dictionary<string, string> teachers = new Dictionary<string, string>
        {
            {"Math", "Aba"},    // 鍵 "Math" 對應的值是 "Aba"
            {"Science", "Test"} // 鍵 "Science" 對應的值是 "Test"
        };

        // 試圖訪問鍵為 "math" 的值
        // 因為 Dictionary 是區分大小寫的,所以這會產生錯誤
        // Console.WriteLine(teachers["math"]); // error: math != Math

        // 使用 TryGetValue 方法安全地檢查是否存在鍵 "Math"
        // 如果鍵存在,則將對應的值存儲在 result 變量中,並輸出
        // 否,則輸出 "Math not found"
        if (teachers.TryGetValue("Math", out string result))
        {
            Console.WriteLine(result); // 輸出 "Aba"

            // 更改鍵為 "Math" 的值為 "Joe"
            teachers["Math"] = "Joe";
        }
        else
        {
            Console.WriteLine("Math not found"); // 如果鍵 "Math" 不存在則輸出此消息
        }

        // teachers.Remove("Math");

        // 使用 foreach 迴圈遍歷字典,並輸出每個鍵值對
        foreach (var item in teachers)
        {
            // 輸出格式為 "鍵 - 值"
            Console.WriteLine($"{item.Key} - {item.Value}");
        }
    }
}

上一篇
Day6 Dictionary1
系列文
C# 由淺入深7
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言