2012-03-10 84 views
13

最好的办法是做什么。散列集的浅拷贝

HashSet<reference_type> set2 = new HashSet<reference_type>(); 

用这样的foreach遍历集合?

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

或者像这样使用类似unison的东西?

chunk2 = chunk.UnionWith(chunk); // all the elements 

回答

20

使用构造函数:

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

个人而言,我希望LINQ到对象了,因为它确实为ListDictionary一个ToHashSet扩展方法。它很容易地创建,当然你自己:

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

(与另一重载自定义相等比较。)

这可以很容易地创建套匿名类型。

4

这可能是最简单有效的:

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

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

MSDN docs

HashSet<T>(IEnumerable<T> collection) 

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

10

最好是主观的,但我如下做到这一点:

set2 = new HashSet<type>(set); 

甚至更​​好:

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

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