This post will discuss how to check whether an element is present in a HashSet<T> in C#.

1. Using Enumerable.Contains() Method

The Enumerable.Contains() method provides a simple and straightforward way to determine whether a container contains the specified element. It returns true if the container contains an element with the specified value; false otherwise.

Download  Run Code

2. Using Enumerable.Any() Method

The LINQ’s Enumerable.Any() method returns true if any element of a container satisfies the specified condition. You can create an extension method using the Any() method that checks whether an item is present in a HashSet<T>, as shown below.

Download  Run Code

That’s all about checking whether an element is present in a HashSet<T> in C#.