Mid Collections

How do you remove duplicates from a collection using HashSet<T>?

Add all elements from the collection to a HashSet<T>, which automatically removes

duplicates.

Follow:

List<int> numbers = new List<int> { 1, 2, 2, 3, 3, 4 };

HashSet<int> uniqueNumbers = new HashSet<int>(numbers);

Now, uniqueNumbers contains only unique values: {1, 2, 3, 4}.

More from C# Programming Tutorial

All questions for this course