Z
ZHANK
编程在线教程C# 教程Dictionary 与 HashSet
字符串与集合

Dictionary 与 HashSet

Dictionary<K,V> 键值对、HashSet<T> 集合、TryGetValue 模式

Dictionary 与 HashSet

Dictionary<K,V> 是 C# 的哈希表,HashSet<T> 是唯一值集合。配合 LINQ,数据查找从 O(n) 变为 O(1)。

学完本章你将: 掌握 Dictionary 操作、TryGetValue 模式、HashSet 集合运算。


Dictionary

csharp
// 创建
var ages = new Dictionary<string, int>
{
    ["小明"] = 25,
    ["小红"] = 22,
};
ages["小刚"] = 30;  // 添加或覆盖

// 安全的取值(TryGetValue 模式)
if (ages.TryGetValue("小明", out int age))
    Console.WriteLine($"年龄:{age}");
else
    Console.WriteLine("不存在");

// 遍历
foreach (var (name, age) in ages)
    Console.WriteLine($"{name}{age}");

// 常用操作
ages.Remove("小明");              // 删除
bool exists = ages.ContainsKey("小红");
int count = ages.Count;
var keys = ages.Keys;
var values = ages.Values;

HashSet

csharp
var set1 = new HashSet<int> { 1, 2, 3, 4 };
var set2 = new HashSet<int> { 3, 4, 5, 6 };

// 集合运算
set1.IntersectWith(set2);   // {3, 4}(交集)
set1.UnionWith(set2);       // {1,2,3,4,5,6}(并集)
set1.ExceptWith(set2);      // {1, 2}(差集)

set1.Add(7);                 // 添加
bool added = set1.Add(7);   // false(已存在)
set1.Contains(3);            // true

LINQ 转字典

csharp
var list = new[] { "apple", "banana", "cherry" };

// 用 LINQ 创建字典
var dict = list.ToDictionary(
    key => key[0],        // 首字母为键
    value => value.Length // 长度为值
);
// { 'a': 5, 'b': 6, 'c': 6 }

// 分组
var groups = list.GroupBy(s => s.Length);
// { 5: ["apple"], 6: ["banana","cherry"] }