HashSet<T>.Remove(T) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將指定的項目從 HashSet<T> 物件中移除。
public:
virtual bool Remove(T item);
public bool Remove (T item);
abstract member Remove : 'T -> bool
override this.Remove : 'T -> bool
Public Function Remove (item As T) As Boolean
參數
- item
- T
要移除的項目。
傳回
如果成功找到並移除項目則為 true
,否則為 false
。 如果在 HashSet<T> 物件中找不到 item
,則這個方法會傳回 false
。
實作
範例
下列範例示範如何使用 方法,從 HashSet<T> 集合 Remove 中移除值。 在此範例中,會任意從 HashSet<T> 集合中移除零。
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 }
備註
HashSet<T>如果物件不包含指定的專案,則物件會保持不變。 不會擲回任何例外狀況。
這個方法是 O (1) 作業。