Set Operators ใน LINQ
ใช้จัดการ Collections แบบ Set Theory (ทฤษฎีเซต)
1. Union - รวม Unique
รวม 2 Collections ลบค่าซ้ำ (Distinct)
var result = collection1.Union(collection2);
2. Intersect - หาค่าร่วม
คืนค่าที่มีใน ทั้งสอง Collections
var result = collection1.Intersect(collection2);
3. Except - หาค่าต่าง
คืนค่าที่อยู่ใน Collection แรก แต่ไม่อยู่ใน Collection ที่สอง
var result = collection1.Except(collection2);
ตัวอย่างโค้ดครบถ้วน
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers1 = { 1, 2, 3, 4 };
int[] numbers2 = { 2, 4, 7 };
var union = numbers1.Union(numbers2);
var intersect = numbers1.Intersect(numbers2);
var except = numbers1.Except(numbers2);
Console.WriteLine("Union: " + string.Join(", ", union));
Console.WriteLine("Intersect: " + string.Join(", ", intersect));
Console.WriteLine("Except (1 - 2): " + string.Join(", ", except));
// Except ย้อนกลับ
var exceptReverse = numbers2.Except(numbers1);
Console.WriteLine("Except (2 - 1): " + string.Join(", ", exceptReverse));
Console.ReadKey();
}
}
Output
Union: 1, 2, 3, 4, 7 Intersect: 2, 4 Except (1 - 2): 1, 3 Except (2 - 1): 7
การทำงานกับ Object (Complex Type)
ต้อง Implement IEquatable<T> หรือส่ง IEqualityComparer<T>
class Product : IEquatable<Product>
{
public int Id { get; set; }
public string Name { get; set; }
public bool Equals(Product other)
{
return other != null && Id == other.Id;
}
public override int GetHashCode() => Id.GetHashCode();
}
// Usage
var union = products1.Union(products2); // ใช้ Equals/GetHashCode
var unionCustom = products1.Union(products2, new ProductComparer()); // Custom Comparer
Performance & Behavior
| Operator | Deferred? | Streaming? | Complexity |
|---|---|---|---|
| Union | Yes | No (ต้อง Buffer ทั้ง 2) | O(n+m) |
| Intersect | Yes | No | O(n+m) |
| Except | Yes | No | O(n+m) |