การหา Union (รวมค่าที่ไม่ซ้ำ) ของลิสต์ 3 ลิสต์ขึ้นไป ใช้ Enumerable.Union() แบบ Chaining ได้อย่างมีประสิทธิภาพ
ตัวอย่าง: Union 3 ลิสต์
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo
{
public static void Main()
{
var list1 = new List { 3, 4, 5 };
var list2 = new List { 1, 2, 3, 4, 5 };
var list3 = new List { 5, 6, 7, 8 };
// Chain Union: ((list1 ∪ list2) ∪ list3)
var union = list1.Union(list2).Union(list3);
Console.WriteLine("Union of 3 lists:");
foreach (int n in union)
Console.WriteLine(n);
}
}
ผลลัพธ์
3
4
5
1
2
6
7
8
ลำดับของผลลัพธ์
- ค่าจาก list1 ตามลำดับเดิม: 3, 4, 5
- ค่าจาก list2 ที่ไม่อยู่ใน list1: 1, 2
- ค่าจาก list3 ที่ไม่อยู่ใน (list1 ∪ list2): 6, 7, 8
วิธี Alternative: ใช้ HashSet (เร็วกว่าสำหรับข้อมูลเยอะ)
var union = new HashSet(list1);
union.UnionWith(list2);
union.UnionWith(list3);
// union ตอนนี้มี {1,2,3,4,5,6,7,8} - ลำดับไม่รับประกัน
Union กับ Object ต้องใช้ Comparer
var union = list1
.Union(list2, new MyComparer())
.Union(list3, new MyComparer());
กรณีใช้งานจริง
- รวม Tag/Category จากหลายบทความ
- รวม Permission จากหลาย Role (RBAC)
- รวม Keywords จากหลาย Document สำหรับ Search Index
- Feature Flag: รวม Features ที่ Enable จากหลาย Environment
Tip: Union แบบ Distinct + Sorted
var sortedUnion = list1
.Union(list2)
.Union(list3)
.OrderBy(x => x)
.ToList();