How to combine two arrays without duplicate values in C#?
How to combine two arrays without duplicate values in C#?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Ravi Vishwakarma
11-Jun-2024One way to combine two arrays without duplicate values in C# is to use LINQ and the
Unionmethod.Here's how you can do it:
In this example,
Unionis used to mergearray1andarray2. TheUnionthe method returns distinct elements from both arrays. Finally,ToArrayis used to convert the result into an array.Let us create a custom distinct and merge array function with two types.
1. Create a Custom Generic Distinct function
This function returns the unique values from any type of array.
2. Create a function to merge two arrays
Using HashSet:
Using List :
Let's merge the whole code into one program.
Output: