Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Union Method in C#
The Union method in C# is a LINQ extension method that returns the unique elements from both collections. It combines two sequences and automatically removes duplicate values, ensuring each element appears only once in the result.
Syntax
Following is the syntax for the Union method −
public static IEnumerable<TSource> Union<TSource>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second
)
Parameters
-
first − The first sequence to merge.
-
second − The second sequence to merge.
Return Value
Returns an IEnumerable<T> containing the unique elements from both input sequences.
Using Union with Integer Lists
Let us set two lists with some common elements −
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
// two lists with duplicate value 65
var list1 = new List<int>{12, 65, 88, 45};
var list2 = new List<int>{40, 34, 65};
// finding union (removes duplicate 65)
var res = list1.Union(list2);
Console.WriteLine("Union result:");
foreach(int i in res) {
Console.WriteLine(i);
}
}
}
The output of the above code is −
Union result: 12 65 88 45 40 34
Using Union with String Collections
The Union method works with any type, including strings −
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
var fruits1 = new List<string>{"apple", "banana", "cherry"};
var fruits2 = new List<string>{"banana", "date", "elderberry"};
var allFruits = fruits1.Union(fruits2);
Console.WriteLine("All unique fruits:");
foreach(string fruit in allFruits) {
Console.WriteLine(fruit);
}
}
}
The output of the above code is −
All unique fruits: apple banana cherry date elderberry
Union vs Concat Comparison
| Union | Concat |
|---|---|
| Removes duplicate elements automatically | Keeps all elements including duplicates |
| Returns unique elements from both sequences | Simply joins both sequences together |
| Order: first sequence, then new elements from second | Order: first sequence, then all of second sequence |
Conclusion
The Union method in C# provides an efficient way to combine two collections while automatically eliminating duplicates. It preserves the order of elements from the first collection and appends unique elements from the second collection, making it ideal for merging datasets without redundancy.
