当前位置:首页 > C# > 正文

C# 哈希集合操作全解析(并集、交集与差集实战教程)

在 C# 编程中,哈希集合(HashSet)是一种非常高效的数据结构,用于存储不重复的元素。它基于哈希表实现,插入、删除和查找操作的时间复杂度接近 O(1)。除了基本操作外,HashSet<T> 还提供了强大的集合运算功能,包括并集(Union)、交集(Intersect)和差集(Except)。本文将手把手教你如何在 C# 中使用这些操作,即使是编程小白也能轻松掌握!

C# 哈希集合操作全解析(并集、交集与差集实战教程) 哈希集合  HashSet 并集 交集 差集 第1张

什么是 HashSet?

HashSet<T> 是 .NET Framework 提供的一个泛型集合类,位于 System.Collections.Generic 命名空间中。它的最大特点是:自动去重。当你向 HashSet 中添加重复元素时,它会自动忽略。

准备工作:创建两个 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));    }}

1. 并集(Union)——合并所有不重复元素

并集操作将两个集合中的所有元素合并,并自动去除重复项。在 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 不会改变原集合,适合需要保留原始数据的场景。

2. 交集(Intersect)——找出共同元素

交集操作返回两个集合中都存在的元素。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

3. 差集(Except)——排除另一个集合的元素

差集操作从一个集合中移除另一个集合中存在的所有元素。使用 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));    }}

小贴士

  • C# 哈希集合 的这些方法都是就地操作(in-place),会修改原集合。如需保留原数据,请先复制一份。
  • 这些操作对性能要求高的场景非常有用,比如去重、权限比对、用户标签分析等。
  • 除了 intHashSet<T> 也支持自定义对象,但需正确实现 EqualsGetHashCode 方法。

总结

通过本文,你已经掌握了 C# 中 HashSet 并集HashSet 交集HashSet 差集 的基本用法。这些操作不仅简洁高效,还能大大简化集合处理逻辑。希望这篇教程能帮助你在实际项目中灵活运用 C# 哈希集合 的强大功能!