📜  C#|两个HashSet的交集

📅  最后修改于: 2021-05-29 17:07:28             🧑  作者: Mango

HashSet是唯一元素的无序集合。在System.Collections.Generic命名空间中找到它。它用于我们要防止将重复项插入到集合中的情况。就性能而言,与列表相比更好。哈希集.IntersectWith(IEnumerable ) 方法用于修改当前的HashSet对象仅包含该对象和指定集合中存在的元素。

句法:

mySet1.IntersectWith(mySet2)

这里, mySet1mySet2是两个HashSet。

异常:如果HashSet为null,则此方法将提供ArgumentNullException

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code to find Intersection 
//of two HashSets
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HashSet of integers
        HashSet mySet1 = new HashSet();
  
        // Creating a HashSet of integers
        HashSet mySet2 = new HashSet();
  
        // Inserting even numbers less than
        // equal to 10 in HashSet mySet1
        Console.WriteLine("Elements in Set 1 :");
          
        for (int i = 0; i < 5; i++) {
            mySet1.Add(i * 2);
            Console.WriteLine(i * 2);
        }
  
        // Inserting odd numbers less than
        // equal to 10 in HashSet mySet2
        Console.WriteLine("Elements in Set 2 : ");
        for (int i = 0; i < 5; i++) {
            mySet1.Add(i * 2 + 1);
            Console.WriteLine(i *2 + 1);
        }
  
        // Creating a new HashSet that contains
        // the Intersection of both the HashSet mySet1 & mySet2
        HashSet ans = new HashSet(mySet1);
  
        ans.IntersectWith(mySet2);
  
        // Printing the Intersection of both the HashSets
        // It should show no element in the output
        // as there is no element common in both
        // the HashSets
        foreach(int i in ans)
        {
            Console.WriteLine(i);
        }
    }
}
输出:
Elements in Set 1 :
0
2
4
6
8
Elements in Set 2 : 
1
3
5
7
9

范例2:

// C# code to find Intersection
// of two HashSets
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HashSet of strings
        HashSet mySet1 = new HashSet();
  
        // Creating a HashSet of strings
        HashSet mySet2 = new HashSet();
  
        // Inserting elements in mySet1
        mySet1.Add("Hello");
        mySet1.Add("Geeks");
        mySet1.Add("GeeksforGeeks");
  
        // Inserting elements in mySet2
        mySet2.Add("Geeks");
        mySet2.Add("and");
        mySet2.Add("GeeksforGeeks");
        mySet2.Add("are");
        mySet2.Add("the");
        mySet2.Add("best");
  
        // Creating a new HashSet that contains
        // the Intersection of both the HashSet mySet1 & mySet2
        HashSet ans = new HashSet(mySet1);
  
        ans.IntersectWith(mySet2);
  
        // Printing the Intersection of both the HashSet
        foreach(string i in ans)
        {
            Console.WriteLine(i);
        }
    }
}
输出:
Geeks
GeeksforGeeks

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.hashset-1.intersectwith?view=netframework-4.7.2