With a list you can do:
list.AddRange(otherCollection);
There is no add range method in a HashSet
. What is the best way to add another ICollection
to a HashSet
?
A HashSet is an optimized collection of unordered, unique elements that provides fast lookups and high-performance set operations. The HashSet class was first introduced in . NET 3.5 and is part of the System. Collection. Generic namespace.
Comparison methodHashSet uses equal() and hashcode() methods to compare the elements, while TreeSet we can implements compareTo() method of Comparator interface so we have compare() and compareTo() method ,TreeSet does not use equal() and hashcode() method.
You can't.
The equals() method of java. util. HashSet class is used verify the equality of an Object with a HashSet and compare them. The list returns true only if both HashSet contains same elements, irrespective of order.
For HashSet<T>
, the name is UnionWith
.
This is to indicate the distinct way the HashSet
works. You cannot safely Add
a set of random elements to it like in Collections
, some elements may naturally evaporate.
I think that UnionWith
takes its name after "merging with another HashSet
", however, there's an overload for IEnumerable<T>
too.
This is one way:
public static class Extensions { public static bool AddRange<T>(this HashSet<T> source, IEnumerable<T> items) { bool allAdded = true; foreach (T item in items) { allAdded &= source.Add(item); } return allAdded; } }
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