What would you recommend for class that needs to keep a list of unique integers?
I'm going to want to Add() integers to the collection and also check for existence e.g. Contains().
Would be nice to also get them in a list as a string for display, ie. "1, 5, 10, 21".
Thus, HashSet is a generic collection, that does not allow duplicates.
The reason "why" you "should" use a Collection<T> instead of a List<T> is because if you expose a List<T> , then anyone who gets access to your object can modify the items in the list. Whereas Collection<T> is supposed to indicate that you are making your own "Add", "Remove", etc methods.
HashSet is an unordered collection containing unique elements. It has the standard collection operations Add, Remove and Contains, but since it uses a hash-based implementation, these operations are O(1).
What Is LINQ Distinct Method in C#? C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source.
HashSet:
The
HashSet<T>
class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order...The capacity of a
HashSet<T>
object is the number of elements that the object can hold. AHashSet<T>
object's capacity automatically increases as elements are added to the object.The
HashSet<T>
class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of theDictionary<TKey, TValue>
orHashtable
collections. In simple terms, theHashSet<T>
class can be thought of as aDictionary<TKey, TValue>
collection without values.A
HashSet<T>
collection is not sorted and cannot contain duplicate elements...
In my testing, I have found that a Dictionary with a dummy value is faster than a HashSet, when dealing with very large sets of data (100,000+ in my case). I expect this is because the Dictionary allows you to set an initial capacity, but I don't really know. In the case you're describing, I would probably use the Dictionary if I was expecting a very large set of numbers, and then (or as I was adding to the Dictionary, depending on the intent) iterate over it using a string builder, to create the output string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With