Reputation: 14046
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", "Stack", "Overflow"}
?
Upvotes: 15
Views: 16222
Reputation: 21938
Old way of doing this
List<string> temp = arr1.ToList<string>();
foreach (string s in arr1)
{
if (!arr2.Contains(s))
{
temp.Add(s);
}
}
String[] arr3 = temp.ToArray<string>();
New and better way, using .Net Framework 3.5
+ LINQ
string[] arr3 = arr1.Union(arr2).ToArray();
Upvotes: 0
Reputation: 1472
ar2.Union<string>(ar1, StringComparer.CurrentCultureIgnoreCase).ToArray<string>();
Upvotes: 0
Reputation: 23039
string[] arr1 = new string[2]{"Hello", "Stack"};
string[] arr2 = new string[2] { "Stack", "Overflow" };
var arr3 = arr1.Union(arr2).ToArray<string>();
Upvotes: 23
Reputation: 1064014
string[] arr3 = arr1.Union(arr2).ToArray();
(if you have LINQ and a using System.Linq;
directive)
Upvotes: 2