Shallow copy of a hashset

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.

Leave a Comment