Giới thiệu
Để kiểm tra hai đối tượng SortedList có bằng nhau, bạn sử dụng phương thức Equals(object). Lưu ý: Equals mặc định so sánh tham chiếu (reference equality), không so sánh nội dung. Hai SortedList khác nhau nhưng có cùng nội dung sẽ trả về false.
Ví dụ 1: So sánh SortedList khác nhau và tham chiếu trùng nhau
using System;
using System.Collections;
public class Demo
{
public static void Main(String[] args)
{
SortedList list1 = new SortedList();
list1.Add("One", 1);
list1.Add("Two ", 2);
list1.Add("Three ", 3);
list1.Add("Four", 4);
list1.Add("Five", 5);
list1.Add("Six", 6);
list1.Add("Seven ", 7);
list1.Add("Eight ", 8);
list1.Add("Nine", 9);
list1.Add("Ten", 10);
Console.WriteLine("Các phần tử của SortedList1...");
foreach (DictionaryEntry d in list1)
{
Console.WriteLine(d.Key + " " + d.Value);
}
SortedList list2 = new SortedList();
list2.Add("A", "Accessories");
list2.Add("B", "Books");
list2.Add("C", "Smart Wearable Tech");
list2.Add("D", "Home Appliances");
Console.WriteLine("\nCác phần tử của SortedList2...");
foreach (DictionaryEntry d in list2)
{
Console.WriteLine(d.Key + " " + d.Value);
}
SortedList list3 = new SortedList();
list3 = list2; // Gán tham chiếu
Console.WriteLine("\nSortedList2 có bằng SortedList3 không? = " + list3.Equals(list2));
}
}
Kết quả
Các phần tử của SortedList1... Eight 8 Five 5 Four 4 Nine 9 One 1 Seven 7 Six 6 Ten 10 Three 3 Two 2 Các phần tử của SortedList2... A Accessories B Books C Smart Wearable Tech D Home Appliances SortedList2 có bằng SortedList3 không? = True
Ví dụ 2: So sánh hai SortedList khác nhau nhưng cùng nội dung
using System;
using System.Collections;
public class Demo
{
public static void Main(String[] args)
{
SortedList list1 = new SortedList();
list1.Add("One", 1);
list1.Add("Two ", 2);
list1.Add("Three ", 3);
list1.Add("Four", 4);
list1.Add("Five", 5);
list1.Add("Six", 6);
list1.Add("Seven ", 7);
list1.Add("Eight ", 8);
list1.Add("Nine", 9);
list1.Add("Ten", 10);
Console.WriteLine("Các phần tử của SortedList1 (cặp khóa-giá trị)...");
foreach (DictionaryEntry d in list1)
{
Console.WriteLine(d.Key + " " + d.Value);
}
SortedList list2 = new SortedList();
list2.Add("A", "Accessories");
list2.Add("B", "Books");
list2.Add("C", "Smart Wearable Tech");
list2.Add("D", "Home Appliances");
Console.WriteLine("\nCác phần tử của SortedList2 (cặp khóa-giá trị)...");
foreach (DictionaryEntry d in list2)
{
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("\nSortedList2 có bằng SortedList1 không? = " + list2.Equals(list1));
}
}
Kết quả
Các phần tử của SortedList1 (cặp khóa-giá trị)... Eight 8 Five 5 Four 4 Nine 9 One 1 Seven 7 Six 6 Ten 10 Three 3 Two 2 Các phần tử của SortedList2 (cặp khóa-giá trị)... A Accessories B Books C Smart Wearable Tech D Home Appliances SortedList2 có bằng SortedList1 không? = False
Lưu ý quan trọng: SortedList.Equals() so sánh tham chiếu, không so sánh nội dung. Để so sánh nội dung, bạn phải tự viết code duyệt và so sánh từng cặp khóa/giá trị.