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
C# Queryable Union Method
The Queryable Union method in C# performs a set union operation on two sequences, returning all unique elements from both sequences. It removes duplicate elements and preserves the order of first occurrence.
Syntax
Following is the syntax for the Queryable Union method −
public static IQueryable<TSource> Union<TSource>(
this IQueryable<TSource> source1,
IEnumerable<TSource> source2
)
Parameters
source1 − An IQueryable<T> whose distinct elements form the first set for the union.
source2 − An IEnumerable<T> whose distinct elements form the second set for the union.
Return Value
Returns an IQueryable<T> that contains the elements from both input sequences, excluding duplicates.
Using Union with Arrays
The following example demonstrates the Union operation on two integer arrays −
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
public static void Main() {
int[] arr1 = { 29, 40, 15, 55, 70, 30, 90 };
int[] arr2 = { 30, 36, 40, 18, 15, 55, 75 };
IEnumerable<int> result = arr1.AsQueryable().Union(arr2);
Console.WriteLine("Union Result:");
foreach (int num in result) {
Console.WriteLine(num);
}
}
}
The output of the above code is −
Union Result: 29 40 15 55 70 30 90 36 18 75
Using Union with String Collections
Union can also be applied to string collections −
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
public static void Main() {
string[] names1 = { "Alice", "Bob", "Charlie", "David" };
string[] names2 = { "Charlie", "Eve", "Frank", "Alice" };
IEnumerable<string> unionResult = names1.AsQueryable().Union(names2);
Console.WriteLine("Unique Names:");
foreach (string name in unionResult) {
Console.WriteLine(name);
}
}
}
The output of the above code is −
Unique Names: Alice Bob Charlie David Eve Frank
Key Features
Removes Duplicates − Only unique elements appear in the result.
Preserves Order − Elements from the first sequence appear first, followed by unique elements from the second sequence.
Uses Default Equality − Compares elements using their default equality comparer.
Deferred Execution − The query is not executed until the result is enumerated.
Conclusion
The Queryable Union method efficiently combines two sequences by removing duplicates and preserving the order of first occurrence. It's particularly useful for merging datasets while ensuring no duplicate values appear in the final result.
