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

Phương thức SequenceEqual() trong C# Queryable

SequenceEqual() so sánh hai chuỗi có chứa cùng các phần tử, cùng thứ tự và cùng số lượng. Trả về true nếu giống hệt nhau.

Ví dụ minh họa

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

public class Demo
{
    public static void Main()
    {
        Employee emp1 = new Employee { EmployeeRank = 4, EmpName = "Amit", EmpMarks = 90 };
        Employee emp2 = new Employee { EmployeeRank = 5, EmpName = "Raman", EmpMarks = 95 };

        List<Employee> employee1 = new List<Employee> { emp1, emp2 };
        List<Employee> employee2 = new List<Employee> { emp1, emp2 };

        bool res = employee1.AsQueryable().SequenceEqual(employee2);
        Console.WriteLine("Hai danh sách bằng nhau? = " + res);
    }
}

public class Employee
{
    public int EmployeeRank { get; set; }
    public string EmpName { get; set; }
    public int EmpMarks { get; set; }
}

Kết quả đầu ra

Hai danh sách bằng nhau? = True

Lưu ý quan trọng: Mặc định so sánh tham chiếu (reference equality) cho kiểu tham chiếu. Để so sánh giá trị, triển khai IEquatable<T> hoặc dùng overload nhận IEqualityComparer<T>.