If I am not mistaken, some other standard collections have (or can be achieved) similar behavior and, moreover, other collections may have more opportunities than HashSet.

What is the highlight of HashSet and what tasks is it intended for?

  • Why do you sculpt windows and microsoft tags to all questions? - andreycha
  • If you are given an exhaustive answer, mark it as correct (tick the selected answer). - andreycha

1 answer 1

HashSet , unlike ordinary collections, contains unique values. This is a hash table (as Dictionary<K, V> ), in which keys are also values ​​at the same time. Uniqueness is determined by using a hashcode of values ​​and checking them for equality. Therefore, if you use HashSet for your types, you need to correctly override Equals() and GetHashCode() .

Example :

 var set = new HashSet<int>(); Console.WriteLine(set.Add(42) ? "Added" : "Not added"); Console.WriteLine(set.Count); // повторим Console.WriteLine(set.Add(42) ? "Added" : "Not added"); Console.WriteLine(set.Count); 

Common HashSet Usage Scenarios:

  • selection of unique elements from the existing collection (see constructor overload )
  • search for O (1) (for example, if you need to create a collection and then search for it repeatedly, it’s better to use HashSet immediately)