C#中的HashSet是System.Collections.Generic命名空间下的泛型集合类,它存储不重复的元素,并且基于哈希表实现,元素的插入、删除、查找操作的时间复杂度接近O(1),非常适合需要快速去重或者频繁判断元素是否存在的场景。

HashSet的初始化
使用HashSet前需要先引入对应的命名空间,然后通过多种方式完成初始化,常见的方式有以下几种:
using System.Collections.Generic;
// 方式1:无参构造,创建空HashSet
HashSet<int> set1 = new HashSet<int>();
// 方式2:通过现有集合初始化
List<string> nameList = new List<string> { "张三", "李四", "张三" };
HashSet<string> set2 = new HashSet<string>(nameList);
// 方式3:直接初始化元素
HashSet<int> set3 = new HashSet<int> { 1, 2, 3, 4 };
HashSet去重的核心用法
HashSet最核心的特性就是自动去重,当向集合中添加已经存在的元素时,添加操作会返回false,且集合内容不会发生变化,这是它和普通List最大的区别。
HashSet<int> numSet = new HashSet<int>();
// 第一次添加1,返回true
bool addResult1 = numSet.Add(1);
// 再次添加1,返回false,集合不会重复存储
bool addResult2 = numSet.Add(1);
Console.WriteLine($"第一次添加结果:{addResult1}"); // 输出 True
Console.WriteLine($"第二次添加结果:{addResult2}"); // 输出 False
Console.WriteLine($"集合元素数量:{numSet.Count}"); // 输出 1
// 用HashSet对数组去重的示例
int[] duplicateArr = { 1, 2, 2, 3, 3, 3, 4 };
HashSet<int> distinctSet = new HashSet<int>(duplicateArr);
Console.WriteLine(string.Join(",", distinctSet)); // 输出 1,2,3,4
HashSet常用操作方法
基础增删查操作
- Add(T item):向集合添加元素,添加成功返回true,元素已存在返回false
- Remove(T item):从集合中移除指定元素,移除成功返回true,元素不存在返回false
- Contains(T item):判断集合是否包含指定元素,包含返回true,否则返回false
- Clear():清空集合中的所有元素
- Count:获取集合中元素的数量
HashSet<string> fruitSet = new HashSet<string> { "苹果", "香蕉" };
// 添加元素
fruitSet.Add("橙子");
// 判断元素是否存在
bool hasApple = fruitSet.Contains("苹果"); // true
// 移除元素
fruitSet.Remove("香蕉");
// 清空集合
fruitSet.Clear();
Console.WriteLine(fruitSet.Count); // 输出 0
集合运算操作
HashSet还提供了多个集合运算相关的方法,方便处理多个集合之间的关系:
| 方法名 | 作用说明 |
|---|---|
| UnionWith(IEnumerable<T> other) | 求当前集合和另一个集合的并集,结果保存到当前集合 |
| IntersectWith(IEnumerable<T> other) | 求当前集合和另一个集合的交集,结果保存到当前集合 |
| ExceptWith(IEnumerable<T> other) | 求当前集合和另一个集合的差集,结果保存到当前集合 |
| SymmetricExceptWith(IEnumerable<T> other) | 求当前集合和另一个集合的对称差集(仅在一个集合中存在的元素),结果保存到当前集合 |
| IsSubsetOf(IEnumerable<T> other) | 判断当前集合是否是另一个集合的子集 |
| IsSupersetOf(IEnumerable<T> other) | 判断当前集合是否是另一个集合的超集 |
HashSet<int> setA = new HashSet<int> { 1, 2, 3 };
HashSet<int> setB = new HashSet<int> { 3, 4, 5 };
// 求并集,setA变为 {1,2,3,4,5}
setA.UnionWith(setB);
Console.WriteLine("并集结果:" + string.Join(",", setA)); // 输出 1,2,3,4,5
// 重置setA
setA = new HashSet<int> { 1, 2, 3 };
// 求交集,setA变为 {3}
setA.IntersectWith(setB);
Console.WriteLine("交集结果:" + string.Join(",", setA)); // 输出 3
// 重置setA
setA = new HashSet<int> { 1, 2, 3 };
// 求差集,setA变为 {1,2}
setA.ExceptWith(setB);
Console.WriteLine("差集结果:" + string.Join(",", setA)); // 输出 1,2
// 判断子集
HashSet<int> subSet = new HashSet<int> { 1, 2 };
bool isSub = subSet.IsSubsetOf(setA); // true,subSet是setA的子集
使用注意事项
HashSet存储的元素需要正确实现GetHashCode和Equals方法,否则可能出现去重失效的问题。如果是自定义类,建议重写这两个方法,保证相同的业务逻辑对象能被判定为重复。
如果需要保证元素的插入顺序,可以选择OrderedHashSet,不过C#原生没有内置这个类型,需要自行实现或者使用第三方库,普通的HashSet不会记录元素的插入顺序。