I am exploring the HashSet
type, but I don\'t understand where it stands in collections.
Can one use it to replace a List
HashSet
is a data strucutre in the .NET framework that is a capable of representing a mathematical set as an object. In this case, it uses hash codes (the GetHashCode
result of each item) to compare equality of set elements.
A set differs from a list in that it only allows one occurrence of the same element contained within it. HashSet
will just return false
if you try to add a second identical element. Indeed, lookup of elements is very quick (O(1)
time), since the internal data structure is simply a hashtable.
If you're wondering which to use, note that using a List
where HashSet
is appropiate is not the biggest mistake, though it may potentially allow problems where you have undesirable duplicate items in your collection. What is more, lookup (item retrieval) is vastly more efficient - ideally O(1)
(for perfect bucketing) instead of O(n)
time - which is quite important in many scenarios.