Home > Back-end >  How to obtain an item from HashSet depending on a condition in c#
How to obtain an item from HashSet depending on a condition in c#

Time:01-03

In c#, for List data structure, we can specify a condition as a lambda expression for finding single or multiple elements by List.Find(Predicate) or List.FindAll(Predicate) methods. Is there any way to do a similar operation with HashSet?

CodePudding user response:

If you want multiple results you can use Where method:

hash.Where(x => Predicate(x));

If you want a single result you can use the FirstOrDefault method

hash.FirstOrDefault(x => Predicate(x));

CodePudding user response:

Since HashSet implements the IEnumerable interface, you can use extension methods like Where.

So:

var matches = yourHashSet.Where(item => predicate(item));

should work.

  • Related