HashSet是唯一元素的无序集合。在System.Collections.Generic命名空间中找到它。它用于我们要防止将重复项插入到集合中的情况。就性能而言,与列表相比更好。哈希集
句法:
mySet.Contains(T item);
在这里, mySet是HashSet的名称,而item是在HashSet中定位的必需元素
返回类型:如果HashSet,则此方法返回true
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to check if a HashSet
// contains the specified element
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a HashSet of strings
HashSet mySet = new HashSet();
// Inserting elements in HashSet
mySet.Add("DS");
mySet.Add("C++");
mySet.Add("Java");
mySet.Add("JavaScript");
// Check if a HashSet contains
// the specified element
if (mySet.Contains("Java"))
Console.WriteLine("Required Element is present");
else
Console.WriteLine("Required Element is not present");
}
}
输出:
Required Element is present
范例2:
// C# code to check if a HashSet
// contains the specified element
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a HashSet of integers
HashSet mySet = new HashSet();
// Inserting elements in HashSet
for (int i = 0; i < 5; i++) {
mySet.Add(i * 2);
}
// Check if a HashSet contains
// the specified element
if (mySet.Contains(5))
Console.WriteLine("Required Element is present");
else
Console.WriteLine("Required Element is not present");
}
}
输出:
Required Element is not present
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.hashset-1.contains?view=netframework-4.7.2