為什么網(wǎng)站突然打不開品牌關(guān)鍵詞優(yōu)化哪家便宜
在C#中,Dictionary<TKey, TValue>
?是一個(gè)泛型集合類,用于存儲(chǔ)鍵值對(duì)(key-value pairs)。它提供了快速的查找、插入和刪除操作,適合需要根據(jù)鍵快速查找值的場(chǎng)景。以下是?Dictionary
?的基本用法和常見操作:
1.?創(chuàng)建字典
使用?Dictionary<TKey, TValue>
?類創(chuàng)建字典,其中?TKey
?是鍵的類型,TValue
?是值的類型。
// 創(chuàng)建一個(gè)鍵為 string,值為 int 的字典
Dictionary<string, int> ages = new Dictionary<string, int>();
2.?添加鍵值對(duì)
使用?Add
?方法或索引器向字典中添加鍵值對(duì)。
// 使用 Add 方法添加
ages.Add("Alice", 30);
ages.Add("Bob", 25);// 使用索引器添加(如果鍵已存在,會(huì)覆蓋值)
ages["Charlie"] = 35;
3.?訪問值
通過鍵訪問字典中的值。
// 使用索引器訪問
int aliceAge = ages["Alice"];
Console.WriteLine($"Alice's age: {aliceAge}");// 使用 TryGetValue 安全訪問(避免鍵不存在時(shí)拋出異常)
if (ages.TryGetValue("Bob", out int bobAge))
{Console.WriteLine($"Bob's age: {bobAge}");
}
else
{Console.WriteLine("Bob's age not found.");
}
4.?修改值
通過鍵修改字典中的值。
// 修改 Alice 的年齡
ages["Alice"] = 31;
Console.WriteLine($"Alice's new age: {ages["Alice"]}");
5.?刪除鍵值對(duì)
使用?Remove
?方法刪除指定鍵的鍵值對(duì)。
// 刪除鍵為 "Bob" 的鍵值對(duì)
ages.Remove("Bob");// 檢查是否刪除成功
if (!ages.ContainsKey("Bob"))
{Console.WriteLine("Bob's age has been removed.");
}
6.?檢查鍵或值是否存在
使用?ContainsKey
?或?ContainsValue
?方法檢查字典中是否包含指定的鍵或值。
// 檢查鍵是否存在
if (ages.ContainsKey("Alice"))
{Console.WriteLine("Alice is in the dictionary.");
}// 檢查值是否存在
if (ages.ContainsValue(35))
{Console.WriteLine("Someone is 35 years old.");
}
7.?遍歷字典
使用?foreach
?循環(huán)遍歷字典中的鍵值對(duì)。
foreach (var kvp in ages)
{Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}// 單獨(dú)遍歷鍵或值
foreach (var key in ages.Keys)
{Console.WriteLine($"Key: {key}");
}foreach (var value in ages.Values)
{Console.WriteLine($"Value: {value}");
}
8.?清空字典
使用?Clear
?方法清空字典中的所有鍵值對(duì)。
ages.Clear();
Console.WriteLine($"Dictionary count after clearing: {ages.Count}");
9.?獲取字典的大小
使用?Count
?屬性獲取字典中鍵值對(duì)的數(shù)量。
Console.WriteLine($"Number of entries in the dictionary: {ages.Count}");
10.?初始化字典
可以在創(chuàng)建字典時(shí)直接初始化鍵值對(duì)。
Dictionary<string, int> ages = new Dictionary<string, int>
{{ "Alice", 30 },{ "Bob", 25 },{ "Charlie", 35 }
};
11.?處理鍵沖突
如果嘗試添加一個(gè)已經(jīng)存在的鍵,Add
?方法會(huì)拋出?ArgumentException
??梢允褂?ContainsKey
?方法檢查鍵是否存在,或者使用索引器直接賦值。
if (!ages.ContainsKey("Alice"))
{ages.Add("Alice", 30);
}
else
{Console.WriteLine("Alice already exists in the dictionary.");
}
12.?字典的默認(rèn)值
如果嘗試訪問不存在的鍵,索引器會(huì)拋出?KeyNotFoundException
??梢允褂?TryGetValue
?方法避免異常。
if (ages.TryGetValue("David", out int davidAge))
{Console.WriteLine($"David's age: {davidAge}");
}
else
{Console.WriteLine("David's age not found.");
}
13.?使用自定義類型作為鍵
如果使用自定義類型作為鍵,需要確保該類型正確實(shí)現(xiàn)了?Equals
?和?GetHashCode
?方法,以便字典能夠正確比較和查找鍵。
public class Person
{public string Name { get; set; }public int Age { get; set; }public override bool Equals(object obj){if (obj is Person other){return Name == other.Name && Age == other.Age;}return false;}public override int GetHashCode(){return Name.GetHashCode() ^ Age.GetHashCode();}
}// 使用自定義類型作為鍵
Dictionary<Person, string> personDescriptions = new Dictionary<Person, string>
{{ new Person { Name = "Alice", Age = 30 }, "Software Engineer" },{ new Person { Name = "Bob", Age = 25 }, "Data Scientist" }
};
14.?字典的性能
-
查找:
Dictionary
?的查找操作是 O(1) 時(shí)間復(fù)雜度,因?yàn)樗腔诠1韺?shí)現(xiàn)的。 -
插入和刪除:插入和刪除操作的平均時(shí)間復(fù)雜度也是 O(1)。
-
內(nèi)存開銷:由于哈希表的實(shí)現(xiàn),
Dictionary
?會(huì)占用較多的內(nèi)存。
15.?完整示例
以下是一個(gè)完整的示例,展示了字典的常見操作:
using System;
using System.Collections.Generic;class Program
{static void Main(){// 創(chuàng)建并初始化字典Dictionary<string, int> ages = new Dictionary<string, int>{{ "Alice", 30 },{ "Bob", 25 },{ "Charlie", 35 }};// 添加新鍵值對(duì)ages["David"] = 28;// 修改值ages["Alice"] = 31;// 刪除鍵值對(duì)ages.Remove("Bob");// 遍歷字典foreach (var kvp in ages){Console.WriteLine($"{kvp.Key}: {kvp.Value}");}// 檢查鍵是否存在if (ages.ContainsKey("Charlie")){Console.WriteLine("Charlie is in the dictionary.");}// 獲取字典大小Console.WriteLine($"Number of entries: {ages.Count}");}
}