How to Find Union of Two Sets in C# Easily
In C#, you can find the union of two sets using the
HashSet<T> class with its UnionWith method or by using LINQ's Union() method. Both approaches combine elements from two collections without duplicates.Syntax
There are two common ways to find the union of two sets in C#:
- Using HashSet<T>: Create a
HashSet<T>from one collection, then callUnionWith()passing the second collection. - Using LINQ: Call
Union()on one collection and pass the second collection as an argument.
Both methods return a collection with unique elements from both sets.
csharp
HashSet<T> set1 = new HashSet<T>(collection1); set1.UnionWith(collection2); // or using LINQ var union = collection1.Union(collection2);
Example
This example shows how to find the union of two integer sets using both HashSet<int> and LINQ's Union(). It prints the combined unique elements.
csharp
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { var set1 = new HashSet<int> { 1, 2, 3, 4 }; var set2 = new List<int> { 3, 4, 5, 6 }; // Using HashSet.UnionWith set1.UnionWith(set2); Console.WriteLine("Union using HashSet:"); foreach (var item in set1) { Console.Write(item + " "); } Console.WriteLine(); // Using LINQ Union var unionLinq = new List<int> { 1, 2, 3, 4 }.Union(new List<int> { 3, 4, 5, 6 }); Console.WriteLine("Union using LINQ:"); foreach (var item in unionLinq) { Console.Write(item + " "); } Console.WriteLine(); } }
Output
Union using HashSet:
1 2 3 4 5 6
Union using LINQ:
1 2 3 4 5 6
Common Pitfalls
Common mistakes when finding union of sets in C# include:
- Using
Concat()instead ofUnion(), which does not remove duplicates. - Modifying the original collection unintentionally when using
UnionWith()on aHashSet. - Assuming
Union()returns aHashSet—it returns anIEnumerable, so you may need to convert it to a list or set.
csharp
/* Wrong: Concat keeps duplicates */ var list1 = new List<int> {1, 2, 3}; var list2 = new List<int> {3, 4, 5}; var wrongUnion = list1.Concat(list2); // duplicates remain /* Right: Use Union to remove duplicates */ var rightUnion = list1.Union(list2);
Quick Reference
Summary tips for union of two sets in C#:
- Use
HashSet<T>andUnionWith()to modify a set in place. - Use LINQ
Union()to get a new collection without duplicates. - Remember
Union()returnsIEnumerable<T>, so convert if needed. - Avoid
Concat()if you want unique elements.
Key Takeaways
Use HashSet.UnionWith() to combine sets and update the original set.
LINQ's Union() returns a new collection with unique elements from both sets.
Avoid Concat() when you want to remove duplicates in the union.
Union() returns IEnumerable, so convert it to a list or set if needed.
HashSet ensures fast lookups and uniqueness when working with sets.