I\'ve read this question about why it is not possible, but haven\'t found a solution to the problem.
I would like to retrieve an item from a .NET HashSet
What you're asking for was added to .NET Core a year ago, and was recently added to .NET 4.7.2:
In .NET Framework 4.7.2 we have added a few APIs to the standard Collection types that will enable new functionality as follows.
- ‘TryGetValue‘ is added to SortedSet and HashSet to match the Try pattern used in other collection types.
The signature is as follows (found in .NET 4.7.2 and above):
//
// Summary:
// Searches the set for a given value and returns the equal value it finds, if any.
//
// Parameters:
// equalValue:
// The value to search for.
//
// actualValue:
// The value from the set that the search found, or the default value of T when
// the search yielded no match.
//
// Returns:
// A value indicating whether the search was successful.
public bool TryGetValue(T equalValue, out T actualValue);
P.S.: In case you're interested, there is related function they're adding in the future - HashSet.GetOrAdd(T).