OneBite.Dev - Coding blog in a bite size

Remove Duplicates From An Array In C#

Code snippet for how to Remove Duplicates From An Array In C# with sample and detail explanation

Arrays are a fundamental part of programming, and at some point, you may have to deal with duplicate data in an array. If you’re coding in C#, there are a variety of ways to remove these duplicates. This article will present a simple way to remove duplicate values from an array in C#.

Code snippet for Removing Duplicates

First, let’s have a look at our code snippet:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] array = { "A", "B", "C", "A", "B" };

        var distinctArray = array.Distinct().ToArray();

        foreach (var value in distinctArray)
            Console.WriteLine(value);
    }
}

This program effectively removes duplicate values from our string array and prints all unique values onto the console.

Code Explanation for Removing Duplicates

Let’s go through each part of the code for a better understanding.

Firstly, we are using the System and System.Linq namespaces. The System namespace contains fundamental classes and base classes while the System.Linq namespace provides classes and interfaces that support queries that use Language-Integrated Query (LINQ).

using System;
using System.Linq;

We then declare a string array with duplicate elements:

string[] array = { "A", "B", "C", "A", "B" };

The array named ‘array’ contains we have five elements, where “A” and “B” are repetitive.

The next part is where the ‘magic’ happens. We remove the duplicates by using the LINQ method Distinct() on our array.

var distinctArray = array.Distinct().ToArray();

The Distinct() method returns distinct elements from a sequence or list by removing duplicate elements.

The ToArray() method is used to convert the sequence resulted from Distinct() into an array.

Lastly, we print our result:

foreach (var value in distinctArray)
    Console.WriteLine(value);

We use a foreach loop to display each element in distinctArray. It’s the most fitting loop construct when you want to perform an operation on every element of the given array.

The console will output “A”, “B”, and “C”, showing that the duplicate values have been removed successfully.

This is a basic way to remove duplicates from an array in C#. As always, C# provides multiple ways to achieve this functionality, but the use of the Distinct() method is one of the simplest and most readable approaches.

c-sharp