Find duplicate element in C# Array

Few days ago, I posted one tutorial on how to find duplicate elements in JavaScript array, in C# language, the logic will almost remain same, but here we may have some more advantage of linq extended functionality.

Before going thorough following piece of code, you should get familiar with C# Array (if new!).

Task: We have to find and remove duplicate elements from following c# array.

string[] cities = new[] { "Mumbai", "Goa", "Kolkata", "Goa", "Delhi", "Goa", "Pune", "Bnagalore", "Goa", "Pune" };

To work with c# array, we convert the array to list object and then convert it back to array format.

List<string> inputList = new List<string>(inputArray);

Here are the steps:

  • First, we sort the array. Array.Sort(sortedAr);
  • The loop through each item to compare if earlier item is same as current item, if yes, then consider as duplicate item.
  • Add all duplicate items in a new array.
  • Then based on duplicate item array, remove all duplicate elements from original array.
  • While adding each element in duplicate list, make sure the item is not already added there;
    object _dv= duplicates.Find(s => s.Contains(sortedAr[i]));
    if (_dv==null)
    {
    	duplicates.Add(sortedAr[i]);
    }     
    
  • Finally, remove all duplicate values from array, make sure all values are unique.
    inputList.RemoveAll(p=>p == s);
    

Find duplicate item in array

Following method will take a array as input parameter then return an array of duplicate items.

string[] getDuplicates(string[] array1)
    {
        List<string> duplicates = new List<string>();
        string[] sortedAr = array1;
            
        Array.Sort(sortedAr);
        for(int i=0;i<sortedAr.Length-1;i++)
        {
            if (sortedAr[i]== sortedAr[i + 1])
            {
                object _dv= duplicates.Find(s => s.Contains(sortedAr[i]));
                if (_dv==null)
                {
                    duplicates.Add(sortedAr[i]);
                    }                    
            }
        }
        return duplicates.ToArray();
    }
Remove duplicate element from array

Now we write another method for removing all duplicate item from array, and returning an array of unique items

Notice, in code below we first remove all the matching items inputList.RemoveAll(p=>p == s); from array then add one item back to array.

string[] removeDuplicates(string[] inputArray, string[] duplicateValues)
    {
        List<string> result = new List<string>();

        // create a list object from string array 
        List<string> inputList = new List<string>(inputArray);

        foreach (string s in duplicateValues)
        {
            // remove all the items that match the value of s
            inputList.RemoveAll(p=>p == s);

            // remember which item is completely removed; so one instance can be added back.
            result.Add(s);
        }

        // now add those unique value back to the list 
        foreach (string r in result)
        {
            inputList.Add(r);
        }

        return inputList.ToArray();
    }

We are done with code!

Now let’s test the code to see if things are working as expected.

string[] cities = new[] { "Mumbai", "Goa", "Kolkata", "Goa", "Delhi", "Goa", "Pune", "Bnagalore", "Goa", "Pune" };

string[] duplicates= getDuplicates(cities);

// get a comma separated string from c# array 
Console.WriteLine($"Original: {String.Join(",", cities)}");

Console.WriteLine($"Duplicates: {String.Join(",", duplicates)}");

string[] uniqueValues = removeDuplicates(cities, duplicates);
Console.WriteLine($"Unique Values: {String.Join(",", uniqueValues)}");

In above example we have used string array, you write method for integer array with same logic, or write a generic method.

Using distinct method – alternate way

You may be surprised to know, that there is a alternate way to find the unique items, instead of writing all above lines of code, we can get the same result by just writing three lines of code below.

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

string[] cities = new[] { "Mumbai", "Goa", "Kolkata", "Goa", "Delhi", "Goa", "Pune", "Bnagalore", "Goa", "Pune" };

List<string> inputList = new List<string>(cities);

List<string> dList=  inputList.DistinctBy(p=>p).ToList();

Console.WriteLine($"Unique Values: {String.Join(",", dList.ToArray())}");

Using linq distinct method all we can get unique items just by one line of code, we can apply distinct on any field of custom object.

Above code will help you to improve your logical thinking, and give a chance to play with c# programming.

Hope you enjoyed the searching, sorting and removing item from c# array. Share it with friends!

 
Find duplicate Item in C# Array
.Net C# Programming Tutorials
Online Tutorials
C# .net Interview Questions Answers
.Net C# Examples | Join .Net C# Course