VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/how-to-remove-duplicate-values-from-an-array-in-c-sharp/

⇱ How to Remove Duplicate Values From an Array in C#? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Remove Duplicate Values From an Array in C#?

Last Updated : 23 Jul, 2025

To remove duplicate values from an array in C#, you can use different approaches based on your requirements. So to do this we use the Distinct() function. HashSet, Using a Loop.This function gives distinct values from the given sequence. This method will throw ArgumentNullException if the given array is null.  

Example:

Input: int[] arr = { 1, 2, 2, 3, 4, 4, 5 }
Output: 1,2,3,4,5


Choose the approach based on readability, performance requirements, or your familiarity with C#. Generally, LINQ and HashSet approaches are more concise and easier to understand.

1.Distinct() Function

LINQ offers the Distinct() method to easily remove duplicates from an array.

Syntax:

array_name.Distinct()

Example:


Output
1 2 3 4 5 

Explanation:

  • The Distinct() method removes duplicates.
  • ToArray() converts the result back to an array.

2.Using HashSet<T>

The HashSet class automatically removes duplicates because it only allows unique values.

Syntax:

HashSet<int> s = new HashSet<int>(array);

Example:


Output
1 2 3 4 5 

Explanation:

  • A HashSet is created using the original array, which removes duplicates.
  • The HashSet is then copied to a new array to maintain the array format.

3.Using a Loop

You can use a loop to iterate through the array and add elements to a list if they haven’t already been added.


Output
1 2 3 4 5 

Explanation:

  • Iterate through each element of the original array.
  • Add it to the list only if it doesn’t already exist in the list (!uniqueList.Contains(value)).
  • Finally, convert the list to an array using ToArray().
Comment
Article Tags:

Explore