C# HashSet RemoveWhere() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashSet

Definition

In C#, HashSet.RemoveWhere(match) removes every item that passes a test. You describe the test with a small function called a predicate. The method calls your test once for each item and deletes the ones where the answer is true.

The most common way to write the test is a lambda such as n => n % 2 == 0. Read it as "for each n, answer whether n is even". The method returns an int: how many items were removed. It is the safe way to delete during a loop, because the set does the looping for you.

This is an instance member of HashSet<T> (System.Collections.Generic). Call it on a set variable, such as numbers.RemoveWhere(...). A HashSet<T> is a class, so two variables can share one set. It keeps unique items only and does not promise any order.

Syntax

Pass a lambda (or a method name) that takes one item and returns true for items you want deleted.

C#
HashSet<int> numbers = new HashSet<int> { 1, 2, 3, 4, 5, 6 };
int removed = numbers.RemoveWhere(n => n % 2 == 0);   // removes 2, 4, 6
// removed is 3, numbers now holds 1, 3, 5
CallWhat it does
set.RemoveWhere(n => n > 10)A lambda: removes every item bigger than 10.
set.RemoveWhere(IsSmall)Pass the name of a method that matches Predicate<T> (one item in, bool out).
int count = set.RemoveWhere(...)Keep the number of removed items, for example to print a report.

The predicate should only answer true or false; do not change the set inside it. Passing null throws ArgumentNullException. If no item matches, the result is 0 and the set is unchanged.

Library declarations
C#
public int RemoveWhere(Predicate<T> match);

Parameters

ParameterDescription
matchRequired. A Predicate<T>: a lambda or method that takes one item and returns true if that item should be removed. It must not be null.

Return Value

Return ValueDescription
intThe number of items that were removed. It is 0 when nothing matched.

C# Examples

Example 1 — Remove All Even Numbers

Fill a set with 1 to 10 and remove every even number with one lambda. Print the count and a sorted copy.

C#
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        HashSet<int> numbers = new HashSet<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        int removed = numbers.RemoveWhere(n => n % 2 == 0);

        Console.WriteLine(removed);
        Console.WriteLine(numbers.Count);

        List<int> left = new List<int>(numbers);
        left.Sort();
        Console.WriteLine(string.Join(", ", left));
    }
}

How It Works

  1. Read the lambda. n => n % 2 == 0 means "for each item n, is the remainder after dividing by 2 equal to 0?" That is true for even numbers.
  2. Count of removals. 2, 4, 6, 8, and 10 match, so RemoveWhere returns 5, and the set now holds 5 items.
  3. Not sorted by itself. A HashSet does not promise an order, so the program copies the items into a List<int>.
  4. Sort, then print. left.Sort() puts the odd numbers in order, so the last line is always 1, 3, 5, 7, 9.

Example 2 — Remove Names That Start With A

Use a string method inside the lambda to delete every name starting with the letter A.

C#
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        HashSet<string> names = new HashSet<string> { "Asha", "Arun", "Ravi", "Meena" };

        int removed = names.RemoveWhere(s => s.StartsWith("A"));

        Console.WriteLine(removed);
        Console.WriteLine(names.Count);
        Console.WriteLine(names.Contains("Ravi"));
        Console.WriteLine(names.Contains("Asha"));
    }
}

How It Works

  1. Any test works. The lambda parameter s is a string, so you can call string methods such as StartsWith on it.
  2. Two matches. "Asha" and "Arun" start with A, so they are deleted and RemoveWhere returns 2.
  3. Others stay. "Ravi" and "Meena" fail the test, so Count is 2 and Contains("Ravi") is True.
  4. Order-free checks. The program uses counts and Contains only, so the output is the same on every run.

Example 3 — Use a Named Predicate

Write the rule as a normal method, store it in a Predicate<int>, run it twice, and see what happens with null.

C#
using System;
using System.Collections.Generic;

class Program {
    static bool IsSmall(int n) {
        return n < 3;
    }

    static void Main() {
        HashSet<int> numbers = new HashSet<int> { 1, 2, 3, 4, 5 };
        Predicate<int> rule = IsSmall;

        Console.WriteLine(numbers.RemoveWhere(rule));
        Console.WriteLine(numbers.RemoveWhere(rule));
        Console.WriteLine(numbers.Count);

        try {
            numbers.RemoveWhere(null);
        } catch (ArgumentNullException) {
            Console.WriteLine("null predicate");
        }
    }
}

How It Works

  1. Rule as a method. IsSmall takes one int and returns a bool, so it fits the type Predicate<int>.
  2. First call. The items 1 and 2 are smaller than 3, so they are removed and the call returns 2.
  3. Second call. Nothing small is left, so the call returns 0 and the set is not changed. Count is 3.
  4. No rule, no work. Passing null gives RemoveWhere nothing to test with, so it throws ArgumentNullException and the catch block prints a message.

Frequently Asked Questions

It returns an int: the number of items that were removed. The result is 0 when no item matched the rule.
A predicate is a small function that takes one value and returns true or false. In RemoveWhere it is usually written as a lambda such as n => n > 5.
Yes. The set does the looping itself, so you do not break an enumerator by changing the set while you walk through it.
A HashSet has no promised order, so there is nothing to keep. Sort a copy of the items when you need to print them in order.
List has its own RemoveAll method with the same idea. HashSet calls it RemoveWhere.

Next: SetEquals()

Check whether the HashSet and another collection hold exactly the same distinct items, in any order.

SetEquals() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful