C# program to find if an array contains duplicate


Set an array −

int[] arr = {
   89,
   12,
   56,
   89,
};

Now, create a new Dictionary −

var d = new Dictionary < int, int > ();

Using the dictionary method ContainsKey(), find the duplicate elements in the array −

foreach(var res in arr) {
   if (d.ContainsKey(res))
   d[res]++;
   else
   d[res] = 1;
}

Here is the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         int[] arr = {
            89,
            12,
            56,
            89,
         };
         var d = new Dictionary < int, int > ();

         foreach(var res in arr) {
            if (d.ContainsKey(res))
            d[res]++;
            else
            d[res] = 1;
         }
         foreach(var val in d)
         Console.WriteLine("{0} occurred {1} times", val.Key, val.Value);
      }
   }
}

Output

89 occurred 2 times
12 occurred 1 times
56 occurred 1 times

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

861 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements