This post will discuss how to remove duplicates from a list in C# without destroying the original order of the elements.

1. Using HashSet

We know that HashSet<T> does not permit any duplicate elements. Therefore, if we convert the given list (with duplicates) to HashSet<T> and then convert it back to the list, we’ll get a list with all distinct elements.

The following code example demonstrates how to use the HashSet<T> collection for removing duplicates from the list.

Download  Run Code

 
Please note that the above solution creates a new list and destroys the original ordering of the elements. The following code demonstrates how to use HashSet<T> with List’s RemoveAll() method to in-place remove duplicates from the list and maintain the order of elements.

Download  Run Code

2. Using Enumerable.Distinct() method (System.Linq)

To preserve the original order, we can also use LINQ’s Distinct() method. The following code example demonstrates how to use the Distinct() to return distinct elements from a list of integers.

Download  Run Code

3. Using Enumerable.Union() method (System.Linq)

Another solution is to use LINQ’s Union() method, which gives an IEnumerable<T> which contains the elements from two sequences, excluding duplicates. To convert the resultant sequence to a list, call the ToList() method.

Download  Run Code

That’s all about removing duplicates from a List in C#.