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

📅  最后修改于: 2021-05-29 14:19:52             🧑  作者: Mango

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

句法:

mySet1.IsSubsetOf(mySet2);

这里, mySet1mySet2是HashSets。

返回类型:如果HashSet,则此方法返回true object是另一个子集的子集,否则为false

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

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

范例1:

// C# code to Check if a HashSet is
// a subset 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 only contains even numbers less than
        // equal to 10
        for (int i = 1; i <= 5; i++)
            mySet1.Add(2 * i);
  
        // Creating a HashSet of integers
        HashSet mySet2 = new HashSet();
  
        // Inserting elements in HashSet
        // mySet2 contains all numbers from 1 to 10
        for (int i = 1; i <= 10; i++)
            mySet2.Add(i);
  
        // Check if a HashSet mySet1 is a subset
        // of the HashSet mySet2
        Console.WriteLine(mySet1.IsSubsetOf(mySet2));
    }
}
输出:
True

范例2:

// C# code to Check if a HashSet is
// a subset 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();
  
        // Creating a HashSet of integers
        HashSet mySet2 = new HashSet();
  
        // Inserting elements in HashSet mySet2.
        // mySet2 contains all numbers from 1 to 10
        for (int i = 1; i <= 10; i++)
            mySet2.Add(i);
  
        // Check if a HashSet mySet1 is a subset
        // of the HashSet mySet2
        // It should return true, as an empty HashSet is
        // subset of other HashSet
        Console.WriteLine(mySet1.IsSubsetOf(mySet2));
    }
}
输出:
True

参考:

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