Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 222
alan2here Avatar asked Mar 10 '12 17:03

alan2here


People also ask

How do you make a shallow copy of a HashSet?

clone() method is used to return a shallow copy of the mentioned hash set. It just creates a copy of the set. Parameters: The method does not take any parameters. Return Value: The method just returns a copy of the HashSet.

What is the shallow copy?

A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made.

What copy technique internally used by HashSet clone () method?

Q2. What copy technique internally used by HashSet clone() method ? There are two copy techniques in every object oriented programming lanuage , deep copy and shallow copy. To create a clone or copy of the Set object, HashSet internally uses shallow copy in clone() method , the elements themselves are not cloned .


1 Answers

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.

like image 171
Jon Skeet Avatar answered Oct 13 '22 11:10

Jon Skeet