c# – Why is List needed<T> if HashSet<T> it is better?

Question:

I began to notice that I had to change the collection type from List<T> to HashSet<T> to improve performance. Well, actually now it seems that I'd rather do HashSets right away, wherever I used to make Lists before. Or are there situations when List is preferable?

Answer:

List<T> is an ordered collection that can contain duplicates.

HashSet<T> is an unordered collection, no duplicates. One of the inconveniences is that you need to implement GetHashCode for elements.

It is not always necessary and possible to use a HashSet . Although in cases where it can be used, there will be a significant performance increase on large collections, since some operations are faster (for example, Contains , Remove , Add are performed in O(1) ).

Scroll to Top