📌  相关文章
📜  C#|检查HashSet是否为指定集合的超集

📅  最后修改于: 2021-05-29 22:30:16             🧑  作者: Mango

HashSet是唯一元素的无序集合。它位于System.Collections.Generic命名空间下。它用于我们要防止将重复项插入到集合中的情况。就性能而言,与列表相比更好。 HashSet .IsSupersetOf(IEnumerable ) 方法用于检查HashSet是否object是否是指定集合的超集。

句法:

mySet1.IsSupersetOf(mySet2);

在这里, mySet1mySet2是两个HashSet。

返回值:如果HashSet对象是另一个子集的超集,则此方法返回True,否则返回False

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

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

范例1:

// C# code to Check if a HashSet is a
// superset of the specified collection
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HashSet of strings
        HashSet mySet1 = new HashSet();
  
        // Inserting elements in HashSet
        mySet1.Add("Geeks");
        mySet1.Add("GeeksQuiz");
  
        // Creating a HashSet of strings
        HashSet mySet2 = new HashSet();
  
        // Inserting elements in HashSet
        mySet2.Add("DS");
        mySet2.Add("C++");
        mySet2.Add("Java");
        mySet2.Add("JavaScript");
        mySet2.Add("GeeksQuiz");
        mySet2.Add("Geeks");
  
        // Check if a HashSet is a superset
        // of the specified collection
        // It should return true as HashSet mySet2
        // is superset of HashSet mySet1
        Console.WriteLine(mySet2.IsSupersetOf(mySet1));
    }
}
输出:
True

范例2:

// C# code to Check if a HashSet is a
// superset of the specified collection
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HashSet of integers
        HashSet mySet1 = new HashSet();
  
        // Inserting elements in HashSet
        mySet1.Add(2);
        mySet1.Add(3);
        mySet1.Add(4);
        mySet1.Add(5);
  
        // Creating a HashSet of integers
        HashSet mySet2 = new HashSet();
  
        // Inserting elements in HashSet
        mySet2.Add(3);
        mySet2.Add(4);
        mySet2.Add(5);
        mySet2.Add(6);
  
        // Check if a HashSet is a superset
        // of the specified collection
        // It should return false as HashSet mySet2
        // is not a superset of HashSet mySet1
        Console.WriteLine(mySet2.IsSupersetOf(mySet1));
    }
}
输出:
False

参考:

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