Phương thức Intersect() trong LINQ trả về các phần tử xuất hiện trong cả hai tập hợp (giao tập). Sử dụng so sánh mặc định (EqualityComparer<T>.Default).
Ví dụ với List
List val1 = new List { 25, 30, 40, 60, 80, 95, 110 };
List val2 = new List { 27, 35, 40, 75, 95, 100, 110 };
var intersection = val1.AsQueryable().Intersect(val2);
// Kết quả: 40, 95, 110
Mã nguồn hoàn chỉnh
using System;
using System.Collections.Generic;
using System.Linq;
class Demo
{
static void Main()
{
List val1 = new List { 25, 30, 40, 60, 80, 95, 110 };
List val2 = new List { 27, 35, 40, 75, 95, 100, 110 };
IEnumerable res = val1.AsQueryable().Intersect(val2);
Console.WriteLine("Giao của hai danh sách:");
foreach (int a in res)
Console.WriteLine(a);
}
}
Kết quả
Giao của hai danh sách...
40
95
110
Intersect với kiểu phức tạp
Cần implement IEquatable<T> hoặc dùng IEqualityComparer<T>:
public class Product : IEquatable
{
public int Id { get; set; }
public string Name { get; set; }
public bool Equals(Product other) => other != null && Id == other.Id;
public override int GetHashCode() => Id.GetHashCode();
}
// Hoặc comparer riêng
var intersect = list1.Intersect(list2, new ProductIdComparer());
Intersect vs Join vs Where
| Phương pháp | Dùng khi | Ví dụ |
|---|---|---|
Intersect | Cùng kiểu, so sánh toàn bộ object/key | ID chung giữa 2 list |
Join | Khác kiểu, join theo key | Order + Customer theo CustomerId |
Where + Contains | Lọc list1 theo key trong list2 | list1.Where(x => list2.Select(y=>y.Id).Contains(x.Id)) |
Lưu ý
- Kết quả không trùng lặp (distinct) - Intersect loại bỏ duplicate.
- Thứ tự không đảm bảo (thường theo thứ tự của list đầu).
- Thực thi trì hoãn (deferred).