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# program to find Union of two or more Lists
The Union operation in C# combines multiple lists while removing duplicate elements. The Union() method from LINQ returns distinct elements from both collections, preserving the order of first occurrence.
Syntax
Following is the syntax for using the Union() method −
var result = list1.Union(list2);
For multiple lists, chain the Union operations −
var result = list1.Union(list2).Union(list3);
Using Union() Method with Two Lists
The The output of the above code is − You can find the union of three or more lists by chaining multiple The output of the above code is − The The output of the above code is − Removes duplicates: Elements appearing in multiple lists are included only once. Preserves order: Elements maintain the order of their first occurrence. Returns IEnumerable: The result can be converted to List using Works with any type: Can be used with integers, strings, custom objects, etc. The Union()
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
var list1 = new List<int>{3, 4, 5};
var list2 = new List<int>{1, 2, 3, 4, 5};
var union = list1.Union(list2);
Console.WriteLine("Union of two lists:");
foreach(int i in union) {
Console.WriteLine(i);
}
}
}
Union of two lists:
3
4
5
1
2
Using Union() Method with Multiple Lists
Union() operations −
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
var list1 = new List<int>{3, 4, 5};
var list2 = new List<int>{1, 2, 3, 4, 5};
var list3 = new List<int>{5, 6, 7, 8};
var result = list1.Union(list2).Union(list3);
Console.WriteLine("Union of three lists:");
foreach(int i in result) {
Console.WriteLine(i);
}
}
}
Union of three lists:
3
4
5
1
2
6
7
8
Using Union() with String Lists
Union() method works with any data 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 union = fruits1.Union(fruits2);
Console.WriteLine("Union of fruit lists:");
foreach(string fruit in union) {
Console.WriteLine(fruit);
}
}
}
Union of fruit lists:
Apple
Banana
Cherry
Date
Elderberry
Key Features
ToList() if needed.Conclusion
Union() method in C# provides an efficient way to combine multiple lists while automatically removing duplicates. It preserves the order of first occurrence and can be chained for multiple lists, making it ideal for set operations in LINQ.
