How to Merge Two Arrays in C# Without Duplicate Values: Techniques and Examples

Category > CSHARP || Published on : Tuesday, March 14, 2023 || Views: 379 || C# arrays merging arrays duplicates Union Concat


In C#, merging two arrays without any duplicate values can be done using various methods. In this article, we will discuss some popular techniques and provide code examples to demonstrate how to merge two arrays in C# without any duplicates.

In C#, combining two arrays without duplicate values can be achieved using a variety of techniques. In this article, we will explore some popular methods to merge two arrays in C# without any duplicate values.

One of the most straightforward approaches to combine two arrays without duplicate values is to use the Union method provided by LINQ. This method takes two arrays as inputs and returns a new array with unique elements.

int[] arr1 = { 1, 2, 3 };
int[] arr2 = { 3, 4, 5 };
int[] arr3 = arr1.Union(arr2).ToArray(); // Result: {1, 2, 3, 4, 5}

Here, we first initialize two arrays named arr1 and arr2 with some values. Then, we use the Union method to combine these two arrays without any duplicates. The resulting array is stored in arr3, which we can print to verify that it contains all unique elements from both input arrays.

Another popular approach is to use the Concat method, which concatenates two arrays and returns a new array that contains all the elements from both arrays. However, this method does not remove any duplicates, so we need to apply an additional step to eliminate them. One way to achieve this is to use the Distinct method after concatenating the arrays.

int[] arr4 = { 1, 2, 3 };
int[] arr5 = { 3, 4, 5 };
int[] arr6 = arr4.Concat(arr5).Distinct().ToArray(); // Result: {1, 2, 3, 4, 5}

In this example, we first initialize two arrays named arr4 and arr5 with some values. Then, we use the Concat method to concatenate these two arrays. Finally, we apply the Distinct method to remove any duplicates from the concatenated array, and store the result in arr6.

There are several other techniques to combine arrays without duplicate values in C#, such as using the Except method or manually iterating through both arrays and adding unique elements to a new array. However, the above approaches are some of the most efficient and commonly used ones.

In conclusion, combining two arrays without duplicate values in C# can be achieved using a variety of methods. We have explored some popular techniques, such as using the Union and Concat methods, and discussed their implementation with code examples. By using these techniques, you can effectively merge arrays in C# without any duplicates.