Dictionary<TKey,TValue>.Remove 方法

定義

多載

Remove(TKey)

將具有指定索引鍵的值從 Dictionary<TKey,TValue> 中移除。

Remove(TKey, TValue)

Dictionary<TKey,TValue> 中移除具有指定索引鍵的值,並將該項目複製到 value 參數。

Remove(TKey)

來源:
Dictionary.cs
來源:
Dictionary.cs
來源:
Dictionary.cs

將具有指定索引鍵的值從 Dictionary<TKey,TValue> 中移除。

C#
public bool Remove (TKey key);

參數

key
TKey

要移除的項目索引鍵。

傳回

如果成功找到並移除項目則為 true,否則為 false。 如果在 false 中找不到 key,則這個方法會傳回 Dictionary<TKey,TValue>

實作

例外狀況

keynull

範例

下列程式代碼範例示範如何使用 方法,從字典 Remove 中移除索引鍵/值組。

此程式代碼範例是針對 Dictionary<TKey,TValue> 類別提供的較大範例的一部分, openWith (是本範例中使用的 Dictionary 名稱) 。

C#
// Use the Remove method to remove a key/value pair.
Console.WriteLine("\nRemove(\"doc\")");
openWith.Remove("doc");

if (!openWith.ContainsKey("doc"))
{
    Console.WriteLine("Key \"doc\" is not found.");
}

備註

Dictionary<TKey,TValue>如果 不包含具有指定索引鍵的專案,則 Dictionary<TKey,TValue> 會保持不變。 不會擲回任何例外狀況。

此方法會接近 O (1) 作業。

僅限 .NET Core 3.0+ :這個變動方法可以安全地呼叫,而不會使實例上的作用中 Dictionary<TKey,TValue> 列舉值失效。 這並不表示線程安全。

另請參閱

適用於

.NET 9 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Remove(TKey, TValue)

來源:
Dictionary.cs
來源:
Dictionary.cs
來源:
Dictionary.cs

Dictionary<TKey,TValue> 中移除具有指定索引鍵的值,並將該項目複製到 value 參數。

C#
public bool Remove (TKey key, out TValue value);

參數

key
TKey

要移除的項目索引鍵。

value
TValue

已移除的項目。

傳回

如果成功找到並移除項目則為 true,否則為 false

例外狀況

keynull

適用於

.NET 9 和其他版本
產品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Standard 2.1