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

0

 


Combining two arrays into one array without duplicates is a common task in C# programming. There are two methods for achieving this: using the HashSet method and using the LINQ method. Let's take a look at both methods in detail.


Method 1: Using the HashSet Method :

The HashSet method is a simple and straightforward way to combine two arrays into one array without duplicates. The HashSet class provides a UnionWith method, which takes two arrays as input and returns a combined array with unique values.

Here is an example of how to use the UnionWith method:


int[] firstArray = { 1, 2, 3, 4, 5 };
int[] secondArray = { 4, 5, 6, 7, 8 };

HashSet<int> hashSet = new HashSet<int>(firstArray);
hashSet.UnionWith(secondArray);

int[] combinedArray = hashSet.ToArray();

In the above example, we have created two arrays, firstArray and secondArray. Then, we create a HashSet object and pass the firstArray to the constructor. After that, we use the UnionWith method to combine firstArray and secondArray into the hashSet object. Finally, we use the ToArray method to convert the hashSet object to an array and store it in the combinedArray variable.

Method 2: Using the LINQ Method :

The LINQ method is another way to combine two arrays into one array without duplicates. The Concat method of the LINQ library is used to combine two arrays, and the Distinct method is used to remove duplicates.

Here is an example of how to use the LINQ method:

int[] firstArray = { 1, 2, 3, 4, 5 };
int[] secondArray = { 4, 5, 6, 7, 8 };

int[] combinedArray = firstArray.Concat(secondArray).Distinct().ToArray();


In the above example, we have created two arrays, firstArray and secondArray. Then, we use the Concat method to combine the two arrays into one array. After that, we use the Distinct method to remove duplicates from the combined array. Finally, we use the ToArray method to convert the combined array to an array and store it in the combinedArray variable.

In conclusion, combining two arrays into one array without duplicates is a common task in C# programming. Both the HashSet method and the LINQ method provide an efficient way to achieve this. So, make sure to practice these methods and add them to your toolkit as a C# programmer.


Post a Comment

0Comments
Post a Comment (0)

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

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