Search code examples
c#collectionsuniontraversalshallow-copy

Shallow copy of a hashset


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

Solution

  • 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.