Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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#




// C# program to remove duplicate elements from the array
using System;
using System.Linq;
  
class GFG{
  
public static void Main()
{
      
    // Declare an array of integer type
    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));
      
    // Use distinct() function
    // To create an array that contain distinct values
    int[] unique = data.Distinct().ToArray();
      
    // Display the final result
    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#




// C# program to remove duplicate elements from the array
using System;
using System.Linq;
  
class GFG{
  
public static void Main()
{
      
    // Declare an array of string type
    string[] data1 = { "Java", "Java", "C", "Python", "CPP", "C" };
    Console.WriteLine("Array before removing duplicate values: ");
    Array.ForEach(data1, i => Console.WriteLine(i));
      
    // Use distinct() function
    // To create an array that contain distinct values
    string[] unique = data1.Distinct().ToArray();
      
    // Display the final result
    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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!