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 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);
      }
   }
}

The output of the above code is −

Union of two lists:
3
4
5
1
2

Using Union() Method with Multiple Lists

You can find the union of three or more lists by chaining multiple 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);
      }
   }
}

The output of the above code is −

Union of three lists:
3
4
5
1
2
6
7
8

Using Union() with String Lists

The 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);
      }
   }
}

The output of the above code is −

Union of fruit lists:
Apple
Banana
Cherry
Date
Elderberry

Key Features

  • 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 ToList() if needed.

  • Works with any type: Can be used with integers, strings, custom objects, etc.

Conclusion

The 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.

Updated on: 2026-03-17T07:04:35+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements