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#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG{
public static void Main()
{
int [] array1 = { 22, 33, 21, 34, 56, 32 };
int [] array2 = { 24, 33, 21, 34, 22 };
Console.WriteLine( "Array 1: " );
foreach ( int x1 in array1)
{
Console.WriteLine(x1);
}
Console.WriteLine( "Array 2: " );
foreach ( int x2 in array2)
{
Console.WriteLine(x2);
}
var final = array1.Union(array2).ToArray();
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#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG{
public static void Main()
{
string [] array1 = { "ojaswi" , "gnanesh" , "bobby" };
string [] array2 = { "rohith" , "ojaswi" , "bobby" };
Console.WriteLine( "Array 1: " );
foreach ( string x1 in array1)
{
Console.WriteLine(x1);
}
Console.WriteLine( "\nArray 2: " );
foreach ( string x2 in array2)
{
Console.WriteLine(x2);
}
IEnumerable< string > final1 = array1.Union(array2);
Console.WriteLine( "\nNew 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
Last Updated :
01 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...