Home > database >  C# Array Merge Without Duplicates
C# Array Merge Without Duplicates

Time:11-05

Let's say I have these two arrays:

string[] arr1 = new string[2]{"Hello", "Stack"}
string[] arr2 = new string[2]{"Stack", "Overflow"}

How would I merge them to get a third array like so: string[3]{"Hello", "Overflow"}?

CodePudding user response:

You can do it with a help of Linq:

using System.Linq;

...

var result = arr1
  .Concat(arr2)
  .GroupBy(item => item)  
  .Where(group => group.Count() == 1)
  .Select(group => group.Key)
  .ToArray();

Here we

  1. Concat arrays to get {Hello, Stack, Stack, Overflow}
  2. GroupBy items to have {{Hello}, {Stack, Stack}, {Overflow}} groups
  3. Filter to have groups with 1 item only: {Hello}, {Overflow}
  4. Materialize groups to {Hello, Overflow} array

CodePudding user response:

One way would be to use the Concat, distinct, and toarray methods. Like this:

string[] arr3 = arr1.Concat(arr2).Distinct().ToArray();

CodePudding user response:

Since it has already been answered, I will only provide some additional information.

You can use another structure for storing unique data: HashSet<T>

HashSet<string> set = new HashSet<string>(arr1);
set.UnionWith(arr2);
string[] arr3 = set.ToArray();  

It's just another option, I'm not saying whether it's more performant or not.
Here is an interesting topic: What's better for creating distinct data structures: HashSet or Linq's Distinct()?

  •  Tags:  
  • c#
  • Related