【问题标题】:Hashset Concatenate using Linq使用 Linq 连接哈希集
【发布时间】:2017-09-28 01:35:45
【问题描述】:

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

   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); 

有什么解决办法吗?

【问题讨论】:

    标签: c# linq hashset


    【解决方案1】:

    不要将LinqHashset 一起使用(如果可能)。 Hashset 是出于性能原因而设计的,使用 LINQ 除了创建新集合之外,还会带来性能损失

    而不是Linq union 使用内置UnionWith

    你的 hashset 1 将包含一个连接

       hashSet1.UnionWith(hashSet2); 
    

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

    【讨论】:

    • Do not use Linq with Hashset use UnionWith - 原因?
    • @NikhilAgrawal 使用带有 hashset 的 linq 是一个坏主意,原因很简单,Hashset 是为性能而设计的,而 UnionWith 只是一个内置方法,并不意味着创建任何委托或匿名方法,也没有新的方法集合将被创建 AFAK
    猜你喜欢
    • 1970-01-01
    • 2010-11-29
    • 2012-09-16
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 2012-02-09
    • 1970-01-01
    相关资源
    最近更新 更多