How to combine two arrays without duplicate values in C#?

0

 

How to combine two arrays without duplicate values in C#?

In many programming applications, it's essential to combine two arrays without duplicate values. In this blog, we will explore different methods to combine two arrays without duplicate values in C#.

Understanding Combining Arrays in C#:

Combining arrays in C# means merging two arrays into a single array. However, merging two arrays may result in duplicate values in the resulting array. Therefore, it's essential to remove duplicates while combining arrays. There are several methods to combine two arrays without duplicate values in C#.

  1. Using Linq:

One way to combine two arrays without duplicate values in C# is to use the Linq library. Here's an example:


int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int[] result = array1.Union(array2).ToArray();

In this example, we have two arrays, array1 and array2. We are using the Union method from the Linq library to combine these two arrays without duplicate values. The resulting array is stored in the result variable.

  1. Using HashSet:

Another way to combine two arrays without duplicate values in C# is to use the HashSet collection. Here's an example:


int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
HashSet<int> hashSet = new HashSet<int>(array1);
hashSet.UnionWith(array2);
int[] result = hashSet.ToArray();

In this example, we are using the HashSet collection to combine the two arrays without duplicate values. We first create a HashSet from the first array and then use the UnionWith method to add the elements of the second array to the HashSet. Finally, we convert the HashSet to an array and store it in the result variable.

  1. Using Concat and Distinct:

We can also use the Concat and Distinct methods to combine two arrays without duplicate values. Here's an example:


int[] array1 = { 1, 2, 3 };
int[] array2 = { 3, 4, 5 };
int[] result = array1.Concat(array2).Distinct().ToArray();


In this example, we are using the Concat method to combine the two arrays. We then use the Distinct method to remove any duplicate values in the resulting array. Finally, we convert the resulting sequence to an array and store it in the result variable.


In this blog, we explored different methods to combine two arrays without duplicate values in C#. We discussed using the Linq library, HashSet collection, and Concat and Distinct methods. The method you choose to combine two arrays without duplicate values depends on your specific scenario.

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !