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
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With