Ngôn ngữ LINQ - Toán tử Distinct

Phương thức Distinct trong LINQ

Phương thức mở rộng Distinct trả về một tập hợp các phần tử duy nhất từ ​​danh sách đã cho.

Ví dụ dưới đây minh họa sử dụng phương thức Distinct trong LINQ:

IList<string> strList = new List<string>() { "One", "Two", "Three", "Two", "Three" };

IList<int> intList = new List<int>() { 1, 2, 3, 2, 4, 4, 3, 5 };

var distinctList1 = strList.Distinct();
foreach(var str in distinctList1)
{
    Console.WriteLine(str);
}

var distinctList2 = intList.Distinct();
foreach(var i in distinctList2)
    Console.WriteLine(i);

Đây là kết quả khi biên dịch và thực thi chương trình:

One
Two
Three
1
2
3
4
5

Xem ví dụ

Phương thức mở rộng Distinct không so sánh giá trị của các đối tượng kiểu phức tạp. Bạn cần triển khai interface IEqualityComparer<T> để so sánh giá trị của các kiểu phức tạp.

Trong ví dụ sau, lớp StudentComparer triển khai interface IEqualityComparer<Student> để so sánh các đối tượng Student trong danh sách.

public class Student 
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public int Age { get; set; }
}

class StudentComparer : IEqualityComparer<Student>
{
    public bool Equals(Student x, Student y)
    {
        return x.StudentID == y.StudentID &&
            x.StudentName.ToLower() == y.StudentName.ToLower();
    }

    public int GetHashCode(Student obj)
    {
        return obj.StudentID.GetHashCode();
    }
}

Bây giờ, bạn có thể truyền một đối tượng của lớp StudentComparer trên làm tham số trong phương thức Distinct để so sánh các đối tượng Student như dưới đây.

Ví dụ dưới đây minh họa sử dụng lớp StudentComparer làm đối số cho phương thức Distinct trong LINQ:

IList<Student> studentList = new List<Student>() 
{ 
    new Student() { StudentID = 1, StudentName = "John", Age = 18 },
    new Student() { StudentID = 2, StudentName = "Steve", Age = 15 },
    new Student() { StudentID = 3, StudentName = "Bill", Age = 25 },
    new Student() { StudentID = 3, StudentName = "Bill", Age = 25 },
    new Student() { StudentID = 3, StudentName = "Bill", Age = 25 },
    new Student() { StudentID = 3, StudentName = "Bill", Age = 25 },
    new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 } 
};

var distinctStudents = studentList.Distinct(new StudentComparer());
foreach(Student std in distinctStudents)
    Console.WriteLine(std.StudentName);

Đây là kết quả khi biên dịch và thực thi chương trình:

John
Steve
Bill
Ron

Xem ví dụ

Lưu ý: Phương thức mở rộng Distinct không hỗ trợ cú pháp truy vấn trong LINQ.