HashSet<T>.Remove Method

Removes the specified element from a HashSet<T> object.

Namespace:  System.Collections.Generic
Assemblies:   System.Core (in System.Core.dll)
  System.Collections (in System.Collections.dll)

public bool Remove(
	T item
)

Parameters

item
Type: T

The element to remove.

Return Value

Type: System.Boolean
true if the element is successfully found and removed; otherwise, false. This method returns false if item is not found in the HashSet<T> object.

Implements

ICollection<T>.Remove(T)

If the HashSet<T> object does not contain the specified element, the object remains unchanged. No exception is thrown.

This method is an O(1) operation.

The following example demonstrates how to remove values from a HashSet<T> collection using the Remove method. In this example, zero is arbitrarily removed from the HashSet<T> collection.

    static void Main()
    {
        HashSet<int> evenNumbers = new HashSet<int>();

        for (int i = 0; i < 20; i++)
        {
            evenNumbers.Add(i);
        }

        Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
        DisplaySet(evenNumbers);

        evenNumbers.RemoveWhere(isEven);

        Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
        DisplaySet(evenNumbers);

        if (evenNumbers.Contains(0))
        {
            evenNumbers.Remove(0);
        }

        Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
        DisplaySet(evenNumbers);
    }

    private static bool isEven(int i)
    {
        return ((i % 2) == 1);
    }
/* This example produces output similar to the following:
 * evenNumbers contains 20 elements: { 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 }
 * evenNumbers contains 10 elements: { 0 2 4 6 8 10 12 14 16 18 }
 * evenNumbers contains 9 elements: { 2 4 6 8 10 12 14 16 18 }
 */

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2015 Microsoft