How to Remove Duplicate Values from an Array in C#

Category > CSHARP || Published on : Tuesday, March 14, 2023 || Views: 389 || C# array Distinct() HashSet Dictionary unique values.


In C#, an array is a collection of elements of the same type. Sometimes, an array may contain duplicate values, and it becomes necessary to remove them to ensure that each element in the array is unique. This article explores multiple ways to remove duplicate values from an array in C#.

In C#, an array is a collection of elements of the same type. Sometimes, an array may contain duplicate values, and you may need to remove them to ensure that each element in the array is unique. In this article, we will explore how to remove duplicate values from an array in C#.

Method 1: Using the Distinct() Method One of the easiest ways to remove duplicate values from an array in C# is to use the Distinct() method. This method is available in the LINQ library and can be used to remove duplicate elements from any IEnumerable<T> collection.

Example Code:

int[] numbers = { 1, 2, 3, 4, 4, 5, 5, 6 };
int[] uniqueNumbers = numbers.Distinct().ToArray();

Method 2: Using a HashSet Another way to remove duplicate values from an array in C# is to use a HashSet. A HashSet is a collection that does not allow duplicate values. You can create a HashSet from an array and then convert it back to an array.

Example Code:

int[] numbers = { 1, 2, 3, 4, 4, 5, 5, 6 };
HashSet<int> hashSet = new HashSet<int>(numbers);
int[] uniqueNumbers = hashSet.ToArray();

Method 3: Using a Dictionary You can also use a Dictionary to remove duplicate values from an array in C#. A Dictionary is a collection that stores key-value pairs. In this case, we will use the array elements as keys in the dictionary. If a key already exists in the dictionary, we will skip it.

Example Code:

int[] numbers = { 1, 2, 3, 4, 4, 5, 5, 6 };
Dictionary<int, bool> dictionary = new Dictionary<int, bool>();
foreach (int number in numbers)
{
    if (!dictionary.ContainsKey(number))
    {
        dictionary.Add(number, true);
    }
}
int[] uniqueNumbers = dictionary.Keys.ToArray();

In conclusion, there are multiple ways to remove duplicate values from an array in C#. The most common approaches include using the Distinct() method, a HashSet, or a Dictionary. Choose the method that suits your needs the best, and enjoy unique arrays.