Adding Multiple Items To A HashSet In C#
[C#]
Let us take a typical object:
public record Person(string FirstName, string Surname);
If we had a List of Person
objects:
// a list of persons
var personList = new List<Person>();
We can add multiple items using the AddRange method:
personList.AddRange(new[] { new Person("James", "Bond"), new Person("Jason", "Bourne") });
Very straightforward.
If you have a HashSet, however, the story is a little different. A HashSet
does not, in fact, have an AddRange
method.
However, the HashSet has a UnionWith method that you can use for this purpose.
This method takes and IEnumerable as a parameter, and thus supports most collections.
// a hashset of persons
var personHashSet = new HashSet<Person>();
// add multiple people
personHashSet.UnionWith(new[] { new Person("Evelyn", "Salt"), new Person("Napoleon", "Solo") });
// add people from existing collection
personHashSet.UnionWith(personList);
We can verify this simply:
foreach (var person in personHashSet)
Console.WriteLine($"{person.FirstName} {person.Surname}");
This will print the following:
The code is is in my Github.
Happy hacking!