This post will discuss how to remove duplicates from an array in C# without destroying the original ordering of the elements.

1. Using HashSet

We know that HashSet discards the duplicates. The idea is to convert the given array (with duplicates) to a HashSet and then convert the HashSet back to the array. This will result in an array but without any duplicates. Please note that the ordering of the elements will be destroyed when HashSet is used.

The following code example demonstrates how to use the HashSet to remove duplicates from an array.

Download  Run Code

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

The above approach destroys the ordering of the list elements. To preserve the original order, we can use the Enumerable.Distinct() method from the System.Linq namespace, which returns distinct elements from the source sequence.

The following code example demonstrates how to use the Distinct() to return distinct elements from an integer array.

Download  Run Code

That’s all about removing duplicates from an array in C#.