Shallow copy of a hashset

alan2here picture alan2here · Mar 10, 2012 · Viewed 14.5k times · Source

Whats the best way of doing it?

var set2 = new HashSet<reference_type>();

Traverse the set with a foreach like this.

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

Or use something like union like this.

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

Answer

Jon Skeet picture Jon Skeet · Mar 10, 2012

Use the constructor:

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

Personally I wish LINQ to Objects had a ToHashSet extension method as it does for List and Dictionary. It's easy to create your own of course:

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

(With an other overload for a custom equality comparer.)

This makes it easy to create sets of an anonymous type.