Check whether an element is present in a HashSet in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> numbers = new HashSet<int>() { 1, 2, 4, 7 }; int item = 2; bool hasItem = numbers.Contains(item); Console.WriteLine(hasItem); // True } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.Linq; using System.Collections.Generic; public static class Extensions { public static bool Contain<T>(this IEnumerable<T> numbers, T item) { return numbers.Any(x => x.Equals(item)); } } public class Example { public static void Main() { HashSet<int> set = new HashSet<int>() { 1, 2, 4, 7 }; int item = 2; bool hasItem = set.Contain(item); Console.WriteLine(hasItem); // True } } |
That’s all about checking whether an element is present in a HashSet<T> in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)