In C#, HashSet.UnionWith(other) merges another collection into the set you call it on. The result holds every item that was in the set or in other. In Venn diagram words: it joins both circles.
Take A = {1, 2, 3} and B = {3, 4, 5}. After A.UnionWith(B), A is {1, 2, 3, 4, 5}. The shared 3 is stored once, because a set never holds repeats. The set A is changed in place.B stays as it was, and the method returns nothing.
This is an instance member of HashSet<T> (System.Collections.Generic). Call it on a set variable, such as numbers.UnionWith(...). A HashSet<T> is a class, so two variables can share one set. It keeps unique items only and does not promise any order.
Syntax
Call UnionWith on the set you want to grow. The argument can be any IEnumerable<T>: another set, an array, or a list.
C#
HashSet<int> a = new HashSet<int> { 1, 2, 3 };
HashSet<int> b = new HashSet<int> { 3, 4, 5 };
a.UnionWith(b); // a is now {1, 2, 3, 4, 5}
a.UnionWith(new int[] { 9, 10 }); // arrays and lists work too
Call
What it does
a.UnionWith(b)
Adds every item of b to a. a changes, b does not.
a.UnionWith(new int[] { 9, 10 })
Any IEnumerable<T> works, even one with repeated values.
new HashSet<int>(a).UnionWith(b)
Make a copy first when you need to keep the original a unchanged.
Items already in the set are skipped. Items that the comparer calls equal count as the same item. Passing null throws ArgumentNullException. The method is roughly O(n), where n is the number of items in other.
Library declarations
C#
public void UnionWith(IEnumerable<T> other);
Parameters
Parameter
Description
other
Required. The collection whose items are added to the set. It must not be null, and it may contain repeats.
Return Value
Return Value
Description
void
Nothing is returned. The set you called it on now holds the union.
C# Examples
Example 1 — Merge Two Number Sets
Join {1, 2, 3} and {3, 4, 5} and check that the shared 3 appears only once.
C#
using System;
using System.Collections.Generic;
class Program {
static string Show(HashSet<int> set) {
List<int> items = new List<int>(set);
items.Sort();
return "{" + string.Join(", ", items) + "}";
}
static void Main() {
HashSet<int> a = new HashSet<int> { 1, 2, 3 };
HashSet<int> b = new HashSet<int> { 3, 4, 5 };
a.UnionWith(b);
Console.WriteLine(Show(a));
Console.WriteLine(a.Count);
Console.WriteLine(Show(b));
}
}
Output
{1, 2, 3, 4, 5}
5
{3, 4, 5}
How It Works
Two circles. Set a has 1, 2, 3 and set b has 3, 4, 5. Only the number 3 is in both circles.
Grow a.a.UnionWith(b) tries to add 3, 4, and 5 to a. The 3 is already there and is skipped. The 4 and 5 are new.
Five items.a now holds 1, 2, 3, 4, 5, so Count is 5 and not 6.
b is untouched. Only the set on the left of the dot changes. Show sorts a copy, so the printed order is always the same.
Example 2 — Merge Tags From a List
Use a list with a repeated word as the argument. UnionWith accepts any collection and quietly ignores the repeats.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
HashSet<string> tags = new HashSet<string> { "c#", "sql" };
List<string> more = new List<string> { "sql", "web", "web" };
tags.UnionWith(more);
List<string> sorted = new List<string>(tags);
sorted.Sort();
Console.WriteLine(string.Join(", ", sorted));
Console.WriteLine(tags.Count);
Console.WriteLine(more.Count);
}
}
Output
c#, sql, web
3
3
How It Works
Not only sets. The parameter type is IEnumerable<string>, so a List<string> is fine here.
Repeats vanish."sql" is already in tags, and "web" appears twice in the list. The set stores "web" only once.
Sorted copy for printing. A HashSet has no promised order, so the items go into a List<string> and are sorted to print c#, sql, web.
The list is unchanged.more.Count is still 3, because UnionWith only reads from its argument.
Example 3 — Union With Itself, Empty, and Null
See what happens with a set joined to itself, to an empty collection, and to null. Also fill an empty set from another.
C#
using System;
using System.Collections.Generic;
class Program {
static string Show(HashSet<int> set) {
List<int> items = new List<int>(set);
items.Sort();
return "{" + string.Join(", ", items) + "}";
}
static void Main() {
HashSet<int> a = new HashSet<int> { 1, 2 };
a.UnionWith(a);
Console.WriteLine(a.Count);
a.UnionWith(new int[0]);
Console.WriteLine(a.Count);
HashSet<int> empty = new HashSet<int>();
empty.UnionWith(a);
Console.WriteLine(Show(empty));
try {
a.UnionWith(null);
} catch (ArgumentNullException) {
Console.WriteLine("null collection");
}
}
}
Output
2
2
{1, 2}
null collection
How It Works
Itself. Adding a set to itself adds nothing new, so Count stays 2.
Empty argument.new int[0] has no items to add, so the set is unchanged. This is the "join with nothing" case.
Empty receiver. An empty set joined with {1, 2} becomes {1, 2}. In Venn terms, nothing joined with a circle is that circle.
Null is a mistake. There is no collection to read, so UnionWith(null) throws ArgumentNullException. The catch block prints a message.
Frequently Asked Questions
It adds all items from another collection to the set. Items that are already in the set are skipped, so the result holds every item that was in either collection, each once.
No. It changes the set you call it on and returns nothing. Copy first with new HashSet<int>(a) if you need to keep the original.
Yes. The parameter is IEnumerable<T>, so any array, list, or other set works, even if it contains repeated values.
UnionWith throws ArgumentNullException. Check for null first if the collection may be missing.
The result is the same, but UnionWith is shorter and, for another HashSet with the same comparer, can be faster. Use it whenever you are adding a whole collection.