How to Remove Duplicate Values From an Array in C#?
Last Updated :
23 Nov, 2021
An array is a group of homogeneous elements that are referred to by a common name and can contain duplicate values. In C#, we cannot remove elements from the specified array but we can create a new array that contains the distinct elements. So to do this we use the Distinct() function. This function gives distinct values from the given sequence. This method will throw ArgumentNullException if the given array is null.
Syntax:
array_name.Distinct()
where array_name is an input array.
Example:
Input : data = { 10, 20, 230, 34, 56, 10, 12, 34, 56, 56 }
Output :
10
20
230
34
56
12
Input : data = { "java", "java", "c", "python", "cpp", "c" }
Output :
java
c
python
cpp
Approach
1. Create an array with elements of any type like int, string, float, etc.
2. Apply distinct function and convert to array
data.Distinct().ToArray();
3. Here, ToArray() method converts the values in an array.
4. Display the unique elements by iterating through the array
Array.ForEach(unique, i => Console.WriteLine(i));
Example 1:
C#
using System;
using System.Linq;
class GFG{
public static void Main()
{
int [] data = { 10, 20, 230, 34, 56, 10, 12, 34, 56, 56 };
Console.WriteLine( "Array before removing duplicate values: " );
Array.ForEach(data, i => Console.WriteLine(i));
int [] unique = data.Distinct().ToArray();
Console.WriteLine( "Array after removing duplicate values: " );
Array.ForEach(unique, j => Console.WriteLine(j));
}
}
|
Output:
Array before removing duplicate values:
10
20
230
34
56
10
12
34
56
56
Array after removing duplicate values:
10
20
230
34
56
12
Example 2:
C#
using System;
using System.Linq;
class GFG{
public static void Main()
{
string [] data1 = { "Java" , "Java" , "C" , "Python" , "CPP" , "C" };
Console.WriteLine( "Array before removing duplicate values: " );
Array.ForEach(data1, i => Console.WriteLine(i));
string [] unique = data1.Distinct().ToArray();
Console.WriteLine( "Array after removing duplicate values: " );
Array.ForEach(unique, j => Console.WriteLine(j));
}
}
|
Output:
Array before removing duplicate values:
Java
Java
C
Python
CPP
C
Array after removing duplicate values:
Java
C
Python
CPP
Share your thoughts in the comments
Please Login to comment...