![]() |
VOOZH | about |
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}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:
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:
Output:
Array 1: ojaswi gnanesh bobby Array 2: rohith ojaswi bobby New array: ojaswi gnanesh bobby rohith