How to check if array contains a duplicate number using C#?


Firstly, set an array −

int[] arr = {
   87,
   55,
   23,
   87,
   45,
   23,
   98
};

Now declare a dictionary and loop through the array and get the count of all the elements. The value you get from the dictionary displays the occurrence of numbers −

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

Let us see the complete example −

Example

using System;
using System.Collections.Generic;
namespace Demo {
   public class Program {
      public static void Main(string[] args) {
     
         int[] arr = {
            87,
            55,
            23,
            87,
            45,
            23,
            98
         };
         var dict = new Dictionary < int, int > ();
         foreach(var count in arr) {
            if (dict.ContainsKey(count))
            dict[count]++;
            else
            dict[count] = 1;
         }
         foreach(var val in dict)
         Console.WriteLine("{0} occurred {1} times", val.Key, val.Value);
      }
   }
}

Updated on: 22-Jun-2020

856 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements