Hashset使用Linq连接

时间:2017-04-30 10:42:02

标签: c# linq hashset

我想连接两个hashset,但是当我使用Linq时,我得到一个IEnumerable而不是一个新的hashset

   var hashSet1 = new HashSet<string>();
    hashSet1.Add("foo");
    hashSet1.Add("foo1");
    hashSet1.Add("foo2");
    hashSet1.Add("footoexclude");
    var hashSet2 = new HashSet<string>();
    hashSet2.Add("fooh2");
    hashSet2.Add("fooh3");
    hashSet2.Add("foo2h4");
    hashSet2.Add("footoexclude"); 
 var hres = hashSet1.Union(hashSet2); 

有什么解决方案吗?

1 个答案:

答案 0 :(得分:3)

请勿将LinqHashset一起使用(如果可能)。 Hashset是出于性能原因而设计的,除了创建新的

之外,使用LINQ还会引入性能损失

而不是Linq union使用内置UnionWith

你的hashset 1将包含一个串联

   hashSet1.UnionWith(hashSet2); 

UnionWith()方法用于修改HashSet以包含其自身中存在的所有元素以及与其建立联合的其他(IEnumerable)集合中的元素。

相关问题