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

Kiểm tra hai ArrayList có bằng nhau trong C#

Phương thức Equals của ArrayList so sánh tham chiếu (reference equality). Hai ArrayList khác instance nhưng có cùng nội dung sẽ trả về false.

Ví dụ 1: Gán tham chiếu

using System;
using System.Collections;

public class Demo
{
    public static void Main(string[] args)
    {
        ArrayList list1 = new ArrayList();
        list1.Add("A"); list1.Add("B"); list1.Add("C"); list1.Add("D");
        list1.Add("E"); list1.Add("F"); list1.Add("G"); list1.Add("H"); list1.Add("I");

        Console.WriteLine("Phần tử ArrayList1...");
        foreach (string res in list1) Console.WriteLine(res);

        ArrayList list2 = new ArrayList();
        list2.Add("A"); list2.Add("B"); list2.Add("C"); list2.Add("D");
        list2.Add("E"); list2.Add("F"); list2.Add("G"); list2.Add("H"); list2.Add("I");

        Console.WriteLine("Phần tử ArrayList2...");
        foreach (string res in list2) Console.WriteLine(res);

        ArrayList list3 = new ArrayList();
        list3 = list2; // Gán tham chiếu
        Console.WriteLine("ArrayList3 có bằng ArrayList2? = " + list3.Equals(list2));
    }
}

Kết quả

Phần tử ArrayList1... A B C D E F G H I
Phần tử ArrayList2... A B C D E F G H I
ArrayList3 có bằng ArrayList2? = True

Ví dụ 2: Hai instance riêng biệt cùng nội dung

using System;
using System.Collections;

public class Demo
{
    public static void Main(string[] args)
    {
        ArrayList list1 = new ArrayList();
        list1.Add("A"); list1.Add("B"); list1.Add("C"); list1.Add("D");
        list1.Add("E"); list1.Add("F"); list1.Add("G"); list1.Add("H"); list1.Add("I");

        ArrayList list2 = new ArrayList();
        list2.Add("A"); list2.Add("B"); list2.Add("C"); list2.Add("D");
        list2.Add("E"); list2.Add("F"); list2.Add("G"); list2.Add("H"); list2.Add("I");

        Console.WriteLine("ArrayList1 có bằng ArrayList2? = " + list1.Equals(list2));
    }
}

Kết quả

Phần tử ArrayList1... A B C D E F G H I
Phần tử ArrayList2... A B C D F G H I
ArrayList1 có bằng ArrayList2? = False

Lưu ý: Kết quả ví dụ 2 output có chút khác biệt (thiếu "E") nhưng code thêm đầy đủ. Equals vẫn trả về false vì so sánh tham chiếu. Để so sánh nội dung, hãy dùng LINQ SequenceEqual hoặc duyệt thủ công.