This post will discuss how to retrieve an item from a HashSet<T> in C#.

A HashSet<T> stores a set of distinct values in no particular order. Unlike a List<T>, a HashSet<T> doesn’t have any index which can be used to store and retrieve an element in constant time. This post provides an overview of some of the feasible options to accomplish this.

1. Using HashSet<T>.TryGetValue() Method

The .NET Framework 4.7.2 included TryGetValue() method in HashSet<T> class. It searches the set for a specified value and returns a boolean value indicating whether the search was successful. Note that it takes an out parameter for storing the matching value or a default value if the search yielded no match.

Download  Run Code

2. Using Enumerable.Where() Method

Alternatively, you can use the LINQ’s Where() method to filter a sequence of values based on a predicate. The following code example demonstrates the usage of the Where() method to find the specified object in a set.

Download  Run Code

 
Note that any changes in the returned object are reflected in the original Set and vice-versa. For example,

Download  Run Code

That’s all about retrieving an item from a HashSet<T> in C#.