Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently merge string arrays in .NET, keeping distinct values

I'm using .NET 3.5. I have two string arrays, which may share one or more values:

string[] list1 = new string[] { "apple", "orange", "banana" }; string[] list2 = new string[] { "banana", "pear", "grape" }; 

I'd like a way to merge them into one array with no duplicate values:

{ "apple", "orange", "banana", "pear", "grape" } 

I can do this with LINQ:

string[] result = list1.Concat(list2).Distinct().ToArray(); 

but I imagine that's not very efficient for large arrays.

Is there a better way?

like image 443
Jason Anderson Avatar asked Sep 28 '08 17:09

Jason Anderson


Video Answer


1 Answers

string[] result = list1.Union(list2).ToArray(); 

from msdn: "This method excludes duplicates from the return set. This is different behavior to the Concat(TSource) method, which returns all the elements in the input sequences including duplicates."

like image 103
Wonko Avatar answered Oct 25 '22 10:10

Wonko