HashSet<T>.Contains(T) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
确定 HashSet<T> 对象是否包含指定的元素。
public:
virtual bool Contains(T item);
public bool Contains (T item);
abstract member Contains : 'T -> bool
override this.Contains : 'T -> bool
Public Function Contains (item As T) As Boolean
参数
- item
- T
要在 HashSet<T> 对象中查找的元素。
返回
如果 HashSet<T> 对象包含指定的元素,则为 true
;否则为 false
。
实现
示例
以下示例演示如何使用 Remove 方法从HashSet<T>集合中删除值。 在此示例中, Contains 方法验证集是否包含值,然后再将其删除。
HashSet<int> numbers = new HashSet<int>();
for (int i = 0; i < 20; i++) {
numbers.Add(i);
}
// Display all the numbers in the hash table.
Console.Write("numbers contains {0} elements: ", numbers.Count);
DisplaySet(numbers);
// Remove all odd numbers.
numbers.RemoveWhere(IsOdd);
Console.Write("numbers contains {0} elements: ", numbers.Count);
DisplaySet(numbers);
// Check if the hash table contains 0 and, if so, remove it.
if (numbers.Contains(0)) {
numbers.Remove(0);
}
Console.Write("numbers contains {0} elements: ", numbers.Count);
DisplaySet(numbers);
bool IsOdd(int i)
{
return ((i % 2) == 1);
}
void DisplaySet(HashSet<int> set)
{
Console.Write("{");
foreach (int i in set)
Console.Write(" {0}", i);
Console.WriteLine(" }");
}
// This example displays the following output:
// numbers contains 20 elements: { 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 }
// numbers contains 10 elements: { 0 2 4 6 8 10 12 14 16 18 }
// numbers contains 9 elements: { 2 4 6 8 10 12 14 16 18 }
Imports System.Collections.Generic
Module Example
Public Sub Main()
Dim numbers As New HashSet(Of Integer)()
For i As Integer = 0 To 19
numbers.Add(i)
Next i
' Display all the numbers in the hash table.
Console.Write("numbers contains {0} elements: ", numbers.Count)
DisplaySet(numbers)
' Remove all odd numbers.
numbers.RemoveWhere(AddressOf IsOdd)
Console.Write("numbers contains {0} elements: ", numbers.Count)
DisplaySet(numbers)
' Check if the hash table contains 0 and, if so, remove it.
If numbers.Contains(0) Then
numbers.Remove(0)
End If
Console.Write("numbers contains {0} elements: ", numbers.Count)
DisplaySet(numbers)
End Sub
Private Function IsOdd(ByVal i As Integer) As Boolean
Return ((i Mod 2) = 1)
End Function
Private Sub DisplaySet(ByVal coll As HashSet(Of Integer))
Console.Write("{")
For Each i As Integer In coll
Console.Write(" {0}", i)
Next
Console.WriteLine(" }")
End Sub
End Module
' The example displays the following output:
' numbers contains 20 elements: { 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 }
' numbers contains 10 elements: { 0 2 4 6 8 10 12 14 16 18 }
' numbers contains 9 elements: { 2 4 6 8 10 12 14 16 18 }
注解
此方法是 O (1) 操作。