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.
1.Distinct() Function
LINQ offers the Distinct() method to easily remove duplicates from an array.
Syntax:
array_name.Distinct()
Example:
//C# program that demonstrates how to retrieve unique values from an array using the Distinct method
using System;
using System.Linq;
class Program {
static void Main()
{
int[] arr = { 1, 2, 2, 3, 4, 4, 5 };
// Use Distinct to get unique values
int[] distinct = arr.Distinct().ToArray();
foreach(int x in distinct)
{
Console.Write(x+" ");
}
}
}
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:
//C# program that demonstrates how to retrieve unique values from an array using a HashSet.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[] arr = { 1, 2, 2, 3, 4, 4, 5 };
HashSet<int> set = new HashSet<int>(arr);
foreach (int num in set)
{
Console.Write(num + " ");
}
}
}
Output
1 2 3 4 5
Explanation:
- A
HashSetis created using the original array, which removes duplicates. - The
HashSetis 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.
//C# programs that demonstrate how to retrieve unique values from an array using a List
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[] arr = { 1, 2, 2, 3, 4, 4, 5 };
List<int> distinctList = new List<int>();
foreach (int num in arr)
{
if (!distinctList.Contains(num))
{
distinctList.Add(num);
}
}
foreach (int num in distinctList)
{
Console.Write(num + " ");
}
}
}
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().