C# program to print duplicates from a list of integers


To print duplicates from a list of integers, use the ContainsKey.

Below, we have first set the integers.

int[] arr = {
   3,
   6,
   3,
   8,
   9,
   2,
   2
};

Then Dictionary collection is used to get the count of duplicate integers.

Let us see the code to get duplicate integers.

Example

 Live Demo

using System;
using System.Collections.Generic;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         int[] arr = {
            3,
            6,
            3,
            8,
            9,
            2,
            2
         };
         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

3 occurred 2 times
6 occurred 1 times
8 occurred 1 times
9 occurred 1 times
2 occurred 2 times

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

581 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements