在C#中,HashSet 是一个泛型集合类,属于 System.Collections.Generic 命名空间。它基于哈希表实现,存储唯一的元素,并提供添加、移除和查找操作。与 List 和 Dictionary<TKey, TValue> 不同,HashSet 不维护元素的顺序,也不支持使用索引来访问元素。
以下是C#中HashSet的一些基本操作:
初始化:
HashSet<int> hashSet = new HashSet<int>();
添加元素 - 使用 Add 方法将元素添加到 HashSet:
hashSet.Add(1);
尝试添加元素 - 使用 TryAdd 方法在元素不存在时添加元素:
bool added = hashSet.TryAdd(2);
移除元素 - 使用 Remove 方法移除 HashSet 中的元素:
bool removed = hashSet.Remove(1);
检查元素是否存在 - 使用 Contains 方法检查 HashSet 是否包含特定元素:
bool contains = hashSet.Contains(2);
获取 HashSet 中元素的数量 - 使用 Count 属性:
int count = hashSet.Count;
清空 HashSet - 使用 Clear 方法:
hashSet.Clear();
遍历 HashSet - 使用 foreach 循环遍历 HashSet 中的所有元素:
foreach (int item in hashSet)
{
Console.WriteLine(item);
}
获取所有元素 - 使用 ToArray 或 ToList 方法将 HashSet 中的元素转换为数组或列表:
int[] array = hashSet.ToArray();
List<int> list = hashSet.ToList();
集合操作 - HashSet 提供了一些集合操作的方法,如 UnionWith(并集)、IntersectWith(交集)、ExceptWith(差集)、IsSubsetOf(是否为子集)、IsSupersetOf(是否为超集)、Overlaps(重叠)等:
HashSet<int> hashSet2 = new HashSet<int> { 3, 4, 5 };
hashSet.UnionWith(hashSet2); // 并集
hashSet.IntersectWith(hashSet2); // 交集
hashSet.ExceptWith(hashSet2); // 差集
下面是一个简单的C# HashSet 使用示例:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> hashSet = new HashSet<int> { 1, 2, 3 };
// 添加元素
hashSet.Add(4);
// 尝试添加元素
bool added = hashSet.TryAdd(5);
// 移除元素
bool removed = hashSet.Remove(4);
// 检查元素是否存在
bool contains = hashSet.Contains(3);
// 获取 `HashSet` 中元素的数量
int count = hashSet.Count;
// 打印 `HashSet` 中的所有元素
foreach (int item in hashSet)
{
Console.WriteLine(item);
}
// 清空 `HashSet`
hashSet.Clear();
// 集合操作
HashSet<int> hashSet2 = new HashSet<int> { 3, 4, 5 };
hashSet.UnionWith(hashSet2); // 并集操作
Console.WriteLine("Union count: " + hashSet.Count);
}
}
想了解更多游戏开发知识,可以扫描下方二维码,免费领取游戏开发4天训练营课程