2012-03-10 108 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>,則新文件也將不區分大小寫。