Phương thức Except() trong LINQ trả về các phần tử có trong tập hợp thứ nhất nhưng không có trong tập hợp thứ hai (phép trừ tập hợp / set difference).
Ví dụ: List
List list1 = new List { "P", "Q", "R", "S", "T", "U", "V", "W" };
List list2 = new List { "T", "U", "V", "W" };
var diff = list1.Except(list2); // P, Q, R, S
Mã nguồn hoàn chỉnh
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo
{
public static void Main()
{
List list1 = new List();
list1.Add("P"); list1.Add("Q"); list1.Add("R"); list1.Add("S");
list1.Add("T"); list1.Add("U"); list1.Add("V"); list1.Add("W");
List list2 = new List();
list2.Add("T"); list2.Add("U"); list2.Add("V"); list2.Add("W");
Console.WriteLine("Danh sách 1:");
foreach (string v in list1) Console.WriteLine(v);
Console.WriteLine("\nDanh sách 2:");
foreach (string v in list2) Console.WriteLine(v);
IEnumerable list3 = list1.Except(list2);
Console.WriteLine("\nPhần tử chỉ có trong list1:");
foreach (string v in list3) Console.WriteLine(v);
}
}
Kết quả
Danh sách 1:
P
Q
R
S
T
U
V
W
Danh sách 2:
T
U
V
W
Phần tử chỉ có trong list1:
P
Q
R
S
Except vs các phép tập hợp khác
| Phép toán | Phương thức LINQ | Ý nghĩa | Ví dụ (A={1,2,3}, B={3,4,5}) |
|---|---|---|---|
| Giao (Intersection) | Intersect | A ∩ B | {3} |
| Hợp (Union) | Union | A ∪ B | {1,2,3,4,5} |
| Trừ (Difference) | Except | A \ B | {1,2} |
| Đối xứng (SymDiff) | A.Except(B).Union(B.Except(A)) | (A\B) ∪ (B\A) | {1,2,4,5} |
Lưu ý
- Kết quả distinct (không trùng lặp) -
Exceptloại bỏ duplicate. - So sánh mặc định dùng
EqualityComparer<T>.Default. - Cho class phức tạp: implement
IEquatable<T>hoặc truyềnIEqualityComparer<T>. - Thứ tự kết quả theo thứ tự xuất hiện trong tập thứ nhất.
ExceptBy (.NET 6+)
// Lọc theo key selector thay vì toàn bộ object
var diff = list1.ExceptBy(list2.Select(x => x.Id), x => x.Id);