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

Lấy phần tử duy nhất (Distinct) từ chuỗi trong C# LINQ

Distinct() loại bỏ các phần tử trùng lặp, trả về chuỗi chỉ chứa các giá trị duy nhất. Sử dụng so sánh mặc định (EqualityComparer<T>.Default).

Ví dụ minh họa

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

class Demo
{
    static void Main()
    {
        List<int> ID = new List<int> { 120, 111, 250, 111, 120, 300, 399, 450 };

        IEnumerable<int> res = ID.AsQueryable().Distinct();
        foreach (int arr in res)
            Console.WriteLine(arr);
    }
}

Kết quả đầu ra

120
111
250
300
399
450

Lưu ý: Với kiểu phức tạp (class), cần triển khai IEquatable<T> hoặc cung cấp IEqualityComparer<T> cho overload Distinct(comparer).