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

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

Phương thức Equals của HashSet<T> so sánh tham chiếu (reference equality), không so sánh nội dung. Hai biến tham chiếu đến cùng một đối tượng sẽ trả về true.

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

using System;
using System.Collections.Generic;

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

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

        HashSet set2 = new HashSet();
        set2.Add("John"); set2.Add("Jacob"); set2.Add("Ryan"); set2.Add("Tom");
        set2.Add("Andy"); set2.Add("Tim"); set2.Add("Steve"); set2.Add("Mark");

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

        HashSet set3 = new HashSet();
        set3 = set2; // Gán tham chiếu
        Console.WriteLine("HashSet3 có bằng HashSet2? = " + set3.Equals(set2));
    }
}

Kết quả

Phần tử HashSet1... A B C D E F G H
Phần tử HashSet2... John Jacob Ryan Tom Andy Tim Steve Mark
HashSet3 có bằng HashSet2? = True

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

using System;
using System.Collections.Generic;

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

        HashSet set2 = new HashSet();
        set2.Add("John"); set2.Add("Jacob"); set2.Add("Ryan"); set2.Add("Tom");
        set2.Add("Andy"); set2.Add("Tim"); set2.Add("Steve"); set2.Add("Mark");

        Console.WriteLine("HashSet2 có bằng HashSet1? = " + set2.Equals(set1));
    }
}

Kết quả

Phần tử HashSet1... A B C D E F G H
Phần tử HashSet2... John Jacob Ryan Tom Andy Tim Steve Mark
HashSet2 có bằng HashSet1? = False

Mẹo: Để so sánh nội dung, dùng set1.SetEquals(set2).