Blog

Merge array using distinct values from two arrays in c#

Coding Problems (C#)

Merge array using distinct values from two arrays in c#

				
					// C# program to merge two array into a single
// array without duplicate elements
using System;
using System.Collections.Generic;
using System.Linq;
  
class GFG{
  
public static void Main()
{
      
    // Declare first array with integer numbers
    int[] array1 = { 22, 33, 21, 34, 56, 32 };
      
    // Declare second array with integer numbers
    int[] array2 = { 24, 33, 21, 34, 22 };
      
    // Displaying array 1
    Console.WriteLine("Array 1: ");
      
    foreach (int x1 in array1)
    {
        Console.WriteLine(x1);
    }
      
    // Displaying array 2
    Console.WriteLine("Array 2: ");
      
    foreach (int x2 in array2)
    {
        Console.WriteLine(x2);
    }
      
    // Combine the unique elements and convert into array
    var final = array1.Union(array2).ToArray();
      
    // Display the elements in the final array
    Console.WriteLine("New array:");
    Array.ForEach(final, i => Console.WriteLine(i));
}
}

				
			

Output

				
					Array 1: 
22
33
21
34
56
32
Array 2: 
24
33
21
34
22
New array:
22
33
21
34
56
32
24
				
			

Please comment and share if you like this post and tell us about how we can enhance #dotnetcoaching to be the best online dot net tutor site. Thanks

Subhajit

Leave your thought here

Your email address will not be published. Required fields are marked *