Remove duplicates from an array in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System; using System.Collections.Generic; public class Example { public static T[] removeDuplicates<T>(T[] array) { HashSet<T> set = new HashSet<T>(array); T[] result = new T[set.Count]; set.CopyTo(result); return result; } public static void Main() { int[] array = { 2, 3, 3, 4, 1, 2, 5 }; int[] distinct = removeDuplicates(array); Console.WriteLine(String.Join(",", distinct)); } } /* Output: 2,3,4,1,5 */ |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; public class Example { public static void Main() { int[] array = { 2, 3, 3, 4, 1, 2, 5 }; int[] distinct = array.Distinct().ToArray(); Console.WriteLine(String.Join(",", distinct)); } } /* Output: 2,3,4,1,5 */ |
That’s all about removing duplicates from an array in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)