C# program to print all distinct elements of a given integer array in C#

CsharpProgrammingServer Side Programming

We have set an array and a dictionary to get the distinct elements.

int[] arr = {
   88,
   23,
   56,
   96,
   43
};
var d = new Dictionary < int, int > ();

Dictionary collection allows us to get the key and value of a list.

The following is the code to display distinct elements of a given integer array −

Example

 Live Demo

using System;
using System.Collections.Generic;
namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         int[] arr = {
            88,
            23,
            56,
            96,
            43
         };
         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} time", val.Key, val.Value);
      }
   }
}

Output

88 occurred 1 time
23 occurred 1 time
56 occurred 1 time
96 occurred 1 time
43 occurred 1 time
raja
Published on 20-Aug-2018 13:49:48
Advertisements