欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#中的 Dictionary常用操作

 更新時間:2025年03月06日 08:47:36   作者:追逐時光者  
C#中的Dictionary<TKey,TValue>是用于存儲鍵值對集合的泛型類,允許通過鍵快速檢索值,并且具有唯一鍵、動態(tài)大小和無序集合的特性,常用操作包括添加、訪問、修改、刪除元素,以及檢查鍵或值是否存在,本文介紹C#中的 Dictionary常用操作,感興趣的朋友一起看看吧

基本概念

Dictionary<TKey, TValue>是C#中用于存儲鍵值對集合的泛型類,屬于System.Collections.Generic命名空間。它允許使用鍵(Key)來訪問與其關(guān)聯(lián)的值(Value)。其中,TKey表示字典中鍵的類型,TValue表示字典中值的類型。

Dictionary的基本結(jié)構(gòu)

  • 鍵(Key):唯一標(biāo)識集合中的一個元素。鍵是唯一的,不能有重復(fù)。
  • 值(Value):與鍵相關(guān)聯(lián)的數(shù)據(jù)。值可以是任意類型,并且可以有重復(fù)。
  • 鍵值對(KeyValuePair):鍵和值的組合,表示Dictionary中的一個元素。

Dictionary的主要特性

  • 快速訪問:通過鍵可以快速檢索到對應(yīng)的值,平均時間復(fù)雜度接近O(1),因為Dictionary<TKey,TValue>類是作為哈希表實現(xiàn)。
  • 唯一鍵(Key):每個鍵在Dictionary中都是唯一的,不能重復(fù)。
  • 動態(tài)大小:Dictionary的大小可以動態(tài)調(diào)整,當(dāng)元素數(shù)量超過容量時,它會自動擴容。
  • 無序集合:Dictionary中的元素是無序的,不能通過索引來訪問它們。

Dictionary的常用操作

以下是C#中Dictionary的常用操作完整代碼,其中包括添加元素、訪問元素、修改元素、刪除元素、檢查鍵或值是否存在,以及遍歷元素:

public static void DictionaryOperation()
{
    //創(chuàng)建一個Dictionary來存儲學(xué)生學(xué)號ID和姓名
    Dictionary<int, string> studentDic = new Dictionary<int, string>();
    #region 添加元素
    // Add方法(鍵必須唯一)
    studentDic.Add(1, "大姚");
    studentDic.Add(2, "小袁");
    studentDic.Add(3, "Edwin");
    // 索引器語法(鍵不存在時添加,存在時更新)
    studentDic[4] = "Charlie";
    studentDic[5] = "追逐時光者";
    // 安全添加(避免異常)
    bool isAdded = studentDic.TryAdd(6, "小明"); // 返回 false,因鍵已存在
    #endregion
    #region 訪問元素
    // 直接訪問(鍵必須存在,否則會有異常)
    var currentUserName = studentDic[1];
    Console.WriteLine($"當(dāng)前學(xué)生姓名: {currentUserName}");
    // 安全訪問(避免異常)
    if (studentDic.TryGetValue(5, outvar getUserName))
    {
        Console.WriteLine($"UserName:{getUserName}");
    }
    else
    {
        Console.WriteLine("當(dāng)前學(xué)生ID不存在");
    }
    #endregion
    #region
    // 修改元素
    studentDic[2] = "大西瓜";
    Console.WriteLine($"修改后的名稱:{studentDic[2]}");
    #endregion
    #region 刪除元素
    // 刪除元素
    bool isRemoved = studentDic.Remove(3);
    Console.WriteLine($"刪除結(jié)果:{isRemoved}");
    #endregion
    #region 檢查鍵或值是否存在
    // 檢查鍵是否存在
    if (studentDic.ContainsKey(1))
    {
        Console.WriteLine("存在");
    }
    else
    {
        Console.WriteLine("不存在");
    }
    bool isExistcontainsValue = studentDic.ContainsValue("追逐時光者");
    Console.WriteLine($"是否存在:{isExistcontainsValue}");
    #endregion
    #region 遍歷元素
    // 遍歷元素
    foreach (KeyValuePair<int, string> student in studentDic)
    {
        Console.WriteLine($"ID: {student.Key}, Name: {student.Value}");
    }
    // 使用鍵的枚舉器
    foreach (var key in studentDic.Keys)
    {
        Console.WriteLine($"Key: {key}, Value: {studentDic[key]}");
    }
    // 使用值的枚舉器
    foreach (varvaluein studentDic.Values)
    {
        // 注意:這種方式不能直接獲取鍵,只能獲取值
        Console.WriteLine($"Value: {value}");
    }
    #endregion
}

參考文章

到此這篇關(guān)于C#中的 Dictionary常用操作的文章就介紹到這了,更多相關(guān)C# Dictionary內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論