C# How To Remove Duplicates from an Array
Remove Duplicates
Use the Distinct() method from the System.Linq namespace to keep only one of each value:
Example
int[] numbers = {1, 2, 2, 3, 4, 4, 5};
int[] unique = numbers.Distinct().ToArray();
foreach (int num in unique)
{
Console.WriteLine(num);
}
You can also use a HashSet, which can only store each value once:
Example
int[] numbers = {1, 2, 2, 3, 4, 4, 5};
HashSet<int> unique = new HashSet<int>(numbers);
foreach (int num in unique)
{
Console.WriteLine(num);
}
Explanation:Distinct() skips the values it has already seen, and ToArray() turns the result into a new array.
When you create a HashSet from the array, the duplicates are left out automatically.