在 C# 编程中,哈希集合(HashSet)是一种非常高效的数据结构,用于存储不重复的元素。它基于哈希表实现,插入、删除和查找操作的时间复杂度接近 O(1)。除了基本操作外,HashSet<T> 还提供了强大的集合运算功能,包括并集(Union)、交集(Intersect)和差集(Except)。本文将手把手教你如何在 C# 中使用这些操作,即使是编程小白也能轻松掌握!
HashSet<T> 是 .NET Framework 提供的一个泛型集合类,位于 System.Collections.Generic 命名空间中。它的最大特点是:自动去重。当你向 HashSet 中添加重复元素时,它会自动忽略。
在进行集合运算前,我们先创建两个示例集合:
using System;using System.Collections.Generic;class Program{ static void Main() { // 创建第一个 HashSet var setA = new HashSet<int> { 1, 2, 3, 4, 5 }; // 创建第二个 HashSet var setB = new HashSet<int> { 4, 5, 6, 7, 8 }; Console.WriteLine("Set A: " + string.Join(", ", setA)); Console.WriteLine("Set B: " + string.Join(", ", setB)); }} 并集操作将两个集合中的所有元素合并,并自动去除重复项。在 C# 中,可以使用 UnionWith 方法(修改原集合)或 Union LINQ 方法(返回新集合)。
// 使用 UnionWith 修改 setA 本身setA.UnionWith(setB);Console.WriteLine("并集 (Union): " + string.Join(", ", setA));// 输出: 1, 2, 3, 4, 5, 6, 7, 8// 或者使用 LINQ 返回新集合(不修改原集合)var unionSet = setA.Union(setB).ToHashSet(); 注意:UnionWith 会直接修改调用它的集合,而 LINQ 的 Union 不会改变原集合,适合需要保留原始数据的场景。
交集操作返回两个集合中都存在的元素。C# 提供了 IntersectWith 方法。
// 重置 setA 和 setBvar setA = new HashSet<int> { 1, 2, 3, 4, 5 };var setB = new HashSet<int> { 4, 5, 6, 7, 8 };// 计算交集(修改 setA)setA.IntersectWith(setB);Console.WriteLine("交集 (Intersect): " + string.Join(", ", setA));// 输出: 4, 5 差集操作从一个集合中移除另一个集合中存在的所有元素。使用 ExceptWith 方法。
// 重置 setAvar setA = new HashSet<int> { 1, 2, 3, 4, 5 };var setB = new HashSet<int> { 4, 5, 6, 7, 8 };// 从 setA 中移除 setB 中存在的元素setA.ExceptWith(setB);Console.WriteLine("差集 (Except): " + string.Join(", ", setA));// 输出: 1, 2, 3 下面是一个完整的控制台程序,演示了 C# 哈希集合的并交差运算:
using System;using System.Collections.Generic;using System.Linq;class Program{ static void Main() { var setA = new HashSet<int> { 1, 2, 3, 4, 5 }; var setB = new HashSet<int> { 4, 5, 6, 7, 8 }; Console.WriteLine("原始 Set A: " + string.Join(", ", setA)); Console.WriteLine("原始 Set B: " + string.Join(", ", setB)); Console.WriteLine(); // 并集 var union = new HashSet<int>(setA); union.UnionWith(setB); Console.WriteLine("并集: " + string.Join(", ", union)); // 交集 var intersect = new HashSet<int>(setA); intersect.IntersectWith(setB); Console.WriteLine("交集: " + string.Join(", ", intersect)); // 差集(A - B) var except = new HashSet<int>(setA); except.ExceptWith(setB); Console.WriteLine("差集 (A - B): " + string.Join(", ", except)); }} int,HashSet<T> 也支持自定义对象,但需正确实现 Equals 和 GetHashCode 方法。通过本文,你已经掌握了 C# 中 HashSet 并集、HashSet 交集 和 HashSet 差集 的基本用法。这些操作不仅简洁高效,还能大大简化集合处理逻辑。希望这篇教程能帮助你在实际项目中灵活运用 C# 哈希集合 的强大功能!
本文由主机测评网于2025-12-06发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025123611.html