哈希集的浅拷贝

时间:2012-03-10 17:02:01

标签: c# collections union traversal shallow-copy

最好的办法是什么?

var set2 = new HashSet<reference_type>();

用这样的foreach遍历集合。

foreach (var n in set)
    set2.Add(n);

或者使用像这样的联盟之类的东西。

set2 = set.UnionWith(set); // all the elements

3 个答案:

答案 0 :(得分:28)

使用构造函数:

HashSet<type> set2 = new HashSet<type>(set1);

我个人希望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);
}

(自定义相等比较器的其他重载。)

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

答案 1 :(得分:13)

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

set2 = new HashSet<type>(set);

甚至更好:

set2 = new HashSet<type>(set, set.Comparer);

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

答案 2 :(得分:5)

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

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

HashSet<int> t = new HashSet<int>(s);

来自MSDN docs

HashSet<T>(IEnumerable<T> collection)
  

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