Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an AddRange equivalent for a HashSet in C#

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?

like image 372
Stefanos Kargas Avatar asked Mar 07 '13 09:03

Stefanos Kargas


People also ask

What is a HashSet in C?

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.

Does HashSet use equals or compareTo?

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.

Can we sort HashSet in C#?

You can't.

How does a HashSet check equality?

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.


2 Answers

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.

like image 66
quetzalcoatl Avatar answered Sep 17 '22 12:09

quetzalcoatl


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;     } } 
like image 21
RoadieRich Avatar answered Sep 18 '22 12:09

RoadieRich