假设我有这两个数组:
string[] arr1 = new string[2]{"Hello", "Stack"}
string[] arr2 = new string[2]{"Stack", "Overflow"}
如何合并它们以获得第三个数组:string[3]{"Hello", "Stack", "Overflow"}
?
答案 0 :(得分:13)
string[] arr1 = new string[2]{"Hello", "Stack"};
string[] arr2 = new string[2] { "Stack", "Overflow" };
var arr3 = arr1.Union(arr2).ToArray<string>();
答案 1 :(得分:2)
string[] arr3 = arr1.Union(arr2).ToArray();
(如果您有LINQ和using System.Linq;
指令)
答案 2 :(得分:0)
这样做的老方法
List<string> temp = arr1.ToList<string>();
foreach (string s in arr1)
{
if (!arr2.Contains(s))
{
temp.Add(s);
}
}
String[] arr3 = temp.ToArray<string>();
新的更好的方式,使用。Net Framework 3.5
+ LINQ
string[] arr3 = arr1.Union(arr2).ToArray();
答案 3 :(得分:0)
ar2.Union<string>(ar1, StringComparer.CurrentCultureIgnoreCase).ToArray<string>();