C#中的 Dictionary常用操作
基本概念
Dictionary<TKey, TValue>是C#中用于存儲(chǔ)鍵值對(duì)集合的泛型類,屬于System.Collections.Generic命名空間。它允許使用鍵(Key)來訪問與其關(guān)聯(lián)的值(Value)。其中,TKey表示字典中鍵的類型,TValue表示字典中值的類型。
Dictionary的基本結(jié)構(gòu)
- 鍵(Key):唯一標(biāo)識(shí)集合中的一個(gè)元素。鍵是唯一的,不能有重復(fù)。
- 值(Value):與鍵相關(guān)聯(lián)的數(shù)據(jù)。值可以是任意類型,并且可以有重復(fù)。
- 鍵值對(duì)(KeyValuePair):鍵和值的組合,表示Dictionary中的一個(gè)元素。
Dictionary的主要特性
- 快速訪問:通過鍵可以快速檢索到對(duì)應(yīng)的值,平均時(shí)間復(fù)雜度接近O(1),因?yàn)?code>Dictionary<TKey,TValue>類是作為哈希表實(shí)現(xiàn)。
- 唯一鍵(Key):每個(gè)鍵在Dictionary中都是唯一的,不能重復(fù)。
- 動(dòng)態(tài)大小:Dictionary的大小可以動(dòng)態(tài)調(diào)整,當(dāng)元素?cái)?shù)量超過容量時(shí),它會(huì)自動(dòng)擴(kuò)容。
- 無序集合:Dictionary中的元素是無序的,不能通過索引來訪問它們。
Dictionary的常用操作
以下是C#中Dictionary的常用操作完整代碼,其中包括添加元素、訪問元素、修改元素、刪除元素、檢查鍵或值是否存在,以及遍歷元素:
public static void DictionaryOperation()
{
//創(chuàng)建一個(gè)Dictionary來存儲(chǔ)學(xué)生學(xué)號(hào)ID和姓名
Dictionary<int, string> studentDic = new Dictionary<int, string>();
#region 添加元素
// Add方法(鍵必須唯一)
studentDic.Add(1, "大姚");
studentDic.Add(2, "小袁");
studentDic.Add(3, "Edwin");
// 索引器語法(鍵不存在時(shí)添加,存在時(shí)更新)
studentDic[4] = "Charlie";
studentDic[5] = "追逐時(shí)光者";
// 安全添加(避免異常)
bool isAdded = studentDic.TryAdd(6, "小明"); // 返回 false,因鍵已存在
#endregion
#region 訪問元素
// 直接訪問(鍵必須存在,否則會(huì)有異常)
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("追逐時(shí)光者");
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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#反射實(shí)現(xiàn)插件式開發(fā)的過程詳解
插件式架構(gòu),一種全新的、開放性的、高擴(kuò)展性的架構(gòu)體系,插件式架構(gòu)設(shè)計(jì)好處很多,把擴(kuò)展功能從框架中剝離出來,降低了框架的復(fù)雜度,讓框架更容易實(shí)現(xiàn),這篇文章主要介紹了C#反射實(shí)現(xiàn)插件式開發(fā),需要的朋友可以參考下2023-09-09
在Unity中實(shí)現(xiàn)動(dòng)畫的正反播放代碼
這篇文章主要介紹了在Unity中實(shí)現(xiàn)動(dòng)畫的正反播放代碼,非常的實(shí)用,這里推薦給大家,希望大家能夠喜歡。2015-03-03
c# 如何實(shí)現(xiàn)自動(dòng)更新程序
這篇文章主要介紹了如何用c# 自動(dòng)更新程序,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03

