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

Xóa phần tử trùng lặp khỏi List trong C#


Giới thiệu

Phương thức mở rộng Distinct() trong LINQ (System.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ụ cơ bản

List arr1 = new List { 10, 20, 30, 40, 50, 30, 40, 50 };
List distinct = arr1.Distinct().ToList(); // {10, 20, 30, 40, 50}

Ví dụ hoàn chỉnh

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

public class Demo
{
    public static void Main()
    {
        List arr1 = new List();
        arr1.Add(10); arr1.Add(20); arr1.Add(30);
        arr1.Add(40); arr1.Add(50);
        arr1.Add(30); arr1.Add(40); arr1.Add(50);

        Console.WriteLine("Initial List ...");
        foreach (int i in arr1) Console.WriteLine(i);

        List distinct = arr1.Distinct().ToList();

        Console.WriteLine("List after removing duplicates ...");
        foreach (int res in distinct) Console.WriteLine(res);
    }
}

Kết quả

Initial List ...
10
20
30
40
50
30
40
50
List after removing duplicate elements ...
10
20
30
40
50

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

Cho class/struct, cần implement IEquatable<T> hoặc cung cấp IEqualityComparer<T>:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

var products = new List
{
    new Product { Id = 1, Name = "A" },
    new Product { Id = 1, Name = "A" }, // Trùng
    new Product { Id = 2, Name = "B" }
};

// Cách 1: Implement IEquatable trong class Product
// Cách 2: Cung cấp comparer
var distinct = products.Distinct(new ProductComparer()).ToList();

class ProductComparer : IEqualityComparer
{
    public bool Equals(Product x, Product y) => x.Id == y.Id;
    public int GetHashCode(Product obj) => obj.Id.GetHashCode();
}

Lưu ý hiệu suất

  • Distinct() dùng HashSet nội bộ -> O(n) trung bình.
  • Giữ nguyên thứ tự xuất hiện đầu tiên (stable).
  • Dùng ToHashSet() (NET Core 2.0+) nếu chỉ cần set: var set = arr1.ToHashSet();