![]() |
VOOZH | about |
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
Table of Content
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.
LINQ offers the Distinct() method to easily remove duplicates from an array.
Syntax:
array_name.Distinct()
Example:
1 2 3 4 5
Explanation:
Distinct() method removes duplicates.ToArray() converts the result back to an array.HashSet<T>The HashSet class automatically removes duplicates because it only allows unique values.
Syntax:
HashSet<int> s = new HashSet<int>(array);
Example:
1 2 3 4 5
Explanation:
HashSet is created using the original array, which removes duplicates.HashSet is then copied to a new array to maintain the array format.You can use a loop to iterate through the array and add elements to a list if they haven’t already been added.
1 2 3 4 5
Explanation:
!uniqueList.Contains(value)).ToArray().