How to Combine Two Arrays without Duplicate values in C#?
Given two arrays, now our task is to merge or combine these arrays into a single array without duplicate values. So we can do this task using the Union() method. This method combines two arrays by removing duplicated elements in both arrays. If two same elements are there in an array, then it will take the element only once.
Syntax:
first_array.Union(second_array)
Examples:
Input : array1 = {22, 33, 21, 34, 56, 32} array2 = {24, 56, 78, 34, 22} Output : New array = {22, 33, 21, 34, 56, 32, 24, 78} Input : array1 = {1} array2 = {2} Output : New array = {1, 2}
Approach
1. Declare two arrays of any type integer, string, etc.
2. Apply Union() function and convert to array using ToArray() function.
final = array1.Union(array2).ToArray();
3. Now iterate the elements in the final array using ForEach() function.
Array.ForEach(final, i => Console.WriteLine(i));
4. We can also iterate the array using IEnumerable method.
IEnumerable<int> final = array1.Union(array2); foreach (var in final) { Console.WriteLine(i); }
Example 1:
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
Example 2:
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 strings string [] array1 = { "ojaswi" , "gnanesh" , "bobby" }; // Declare second array with also strings string [] array2 = { "rohith" , "ojaswi" , "bobby" }; // Displaying array 1 Console.WriteLine( "Array 1: " ); foreach ( string x1 in array1) { Console.WriteLine(x1); } // Displaying array 2 Console.WriteLine( "\nArray 2: " ); foreach ( string x2 in array2) { Console.WriteLine(x2); } // Combine the unique elements and convert into array IEnumerable< string > final1 = array1.Union(array2); Console.WriteLine( "\nNew array:" ); // Display the elements in the final array foreach ( var j in final1) { Console.WriteLine(j); } } } |
Output:
Array 1: ojaswi gnanesh bobby Array 2: rohith ojaswi bobby New array: ojaswi gnanesh bobby rohith