C# program to find common elements in three arrays using sets

Set three arrays

int[] arr1 = {
   99,
   57,
   63,
   98
};

int[] arr2 = {
   43,
   99,
   33,
   57
};

int[] arr3 = {
   99,
   57,
   42
};

Now set the above elements using HashSet.

// HashSet One
var h1 = new HashSet  (arr1);
// HashSet Two
var h2 = new HashSet  (arr2);
// HashSet Three
var h3 = new HashSet  (arr3);

Let us see the complete code to find common elements.

Example

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

public class Program {
   public static void Main() {
      int[] arr1 = {
         99,
         57,
         63,
         98
      };

      int[] arr2 = {
         43,
         99,
         33,
         57
      };

      int[] arr3 = {
         99,
         57,
         42
      };

      // HashSet One
      var h1 = new HashSet  (arr1);
      // HashSet Two
      var h2 = new HashSet  (arr2);
      // HashSet Three
      var h3 = new HashSet  (arr3);

      // Displaying
      int[] val1 = h1.ToArray();
      Console.WriteLine("Set one...");
      foreach(int val in val1) {
         Console.WriteLine(val);
      }

      //Displaying
      int[] val2 = h2.ToArray();
      Console.WriteLine("Set two...");
      foreach(int val in val2) {
         Console.WriteLine(val);
      }

      //Displaying
      int[] val3 = h3.ToArray();
      Console.WriteLine("Set three...");
      foreach(int val in val3) {
         Console.WriteLine(val);
      }

      int i = 0, j = 0, k = 0;
      Console.WriteLine("Common elements...");
      while (i 
Updated on: 2020-06-22T09:34:05+05:30

592 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements