高效合并字符串数组.NET中,保持不同的值 [英] Efficiently merge string arrays in .NET, keeping distinct values

查看:127
本文介绍了高效合并字符串数组.NET中,保持不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用.NET 3.5。我有两个字符串数组,其可以共享一个或多个值:

 的String [] list1的=新的String [] {苹果,橙色,香蕉};
字符串[] =列表2新的字符串[] {香蕉,鸭梨,葡萄};

我想办法将它们合并成一个数组没有重复值:

  {苹果,橙色,香蕉,鸭梨,葡萄}

我可以用LINQ做到这一点:

 的String []结果= list1.Concat(列表2).Distinct()ToArray的()。

但我想这不是对于大数组非常有效的。

有没有更好的办法?


解决方案

 的String []结果= list1.Union(列表2).ToArray();

:这种方法从设置返回排除重复这是不同的行为到CONCAT(TSource)方法,该方法返回包括重复输入序列中的所有元素。

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?

解决方案

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."

这篇关于高效合并字符串数组.NET中,保持不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆