哈希集的浅拷贝

ala*_*ere 24 c# collections union traversal shallow-copy

这是最好的方式吗?

var set2 = new HashSet<reference_type>();
Run Code Online (Sandbox Code Playgroud)

用这样的foreach遍历集合.

foreach (var n in set)
    set2.Add(n);
Run Code Online (Sandbox Code Playgroud)

或者像这样使用像union这样的东西.

set2 = set.UnionWith(set); // all the elements
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 35

使用构造函数:

HashSet<type> set2 = new HashSet<type>(set1);
Run Code Online (Sandbox Code Playgroud)

我个人希望LINQ to Objects有一个ToHashSet扩展方法,因为它ListDictionary.当然,创建自己的东西很容易:

public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    return new HashSet<T>(source);
}
Run Code Online (Sandbox Code Playgroud)

(使用自定义相等比较器的其他重载.)

这样可以轻松创建匿名类型的集合.

  • 只是更新:LINQ 现在有一个 ToHashSet 扩展方法。 (3认同)

Joe*_*Joe 15

最好是主观的,但我会这样做:

set2 = new HashSet<type>(set);
Run Code Online (Sandbox Code Playgroud)

甚至更好:

set2 = new HashSet<type>(set, set.Comparer);
Run Code Online (Sandbox Code Playgroud)

这确保您使用与原始HashSet相同的相等比较器.例如,如果原始版本不区分大小写HashSet<string>,则新版本也不区分大小写.


Phi*_*hil 5

这可能是最简单和最好的:

HashSet<int> s = new HashSet<int>{1,2,3};

HashSet<int> t = new HashSet<int>(s);
Run Code Online (Sandbox Code Playgroud)

来自MSDN文档:

HashSet<T>(IEnumerable<T> collection)
Run Code Online (Sandbox Code Playgroud)

初始化HashSet类的新实例,该类使用集合类型的默认相等比较器,包含从指定集合复制的元素,并且具有足够的容量来容纳复制的元素数.