Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức Distinct() trong LINQ C#

Phương thức Distinct() trong LINQ trả về các phần tử duy nhất (loại bỏ trùng lặp) từ một chuỗi. So sánh mặc định dùng EqualityComparer<T>.Default.

Ví dụ với List có trùng lặp

List points = new List { 5, 10, 5, 20, 30, 30, 40, 50, 60, 70 };
var distinct = points.AsQueryable().Distinct();
// Kết quả: 5, 10, 20, 30, 40, 50, 60, 70

Mã nguồn hoàn chỉnh

using System;
using System.Linq;
using System.Collections.Generic;

class Demo
{
    static void Main()
    {
        List points = new List { 5, 10, 5, 20, 30, 30, 40, 50, 60, 70 };
        
        // Lấy phần tử duy nhất
        IEnumerable res = points.AsQueryable().Distinct();
        
        foreach (int a in res)
            Console.WriteLine(a);
    }
}

Kết quả

5
10
20
30
40
50
60
70

Distinct với kiểu phức tạp (Custom Equality)

Mặc định Distinct() so sánh tham chiếu cho reference type. Cần implement IEquatable<T> hoặc cung cấp 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 dùng comparer riêng
var distinctProducts = products.Distinct(new ProductComparer());

DistinctBy (C# 9+ / .NET 6+ / MoreLINQ)

// Lấy distinct theo property cụ thể
var distinctByName = people.DistinctBy(p => p.Name);

Lưu ý

  • Thứ tự phần tử được giữ nguyên (stable) - phần tử đầu tiên xuất hiện được giữ lại.
  • Thực thi trì hoãn (deferred execution).
  • Với IQueryable (EF Core), dịch sang SELECT DISTINCT SQL.