Giới thiệu
Để kiểm tra hai OrderedDictionary có bằng nhau, bạn sử dụng phương thức Equals(object). Tương tự SortedList, phương thức này so sánh **tham chiếu** (reference equality), không so sánh nội dung.
Ví dụ 1: Hai OrderedDictionary khác nhau
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
OrderedDictionary dict1 = new OrderedDictionary();
dict1.Add("A", "Books");
dict1.Add("B", "Electronics");
dict1.Add("C", "Smart Wearables");
dict1.Add("D", "Pet Supplies");
dict1.Add("E", "Clothing");
dict1.Add("F", "Footwear");
Console.WriteLine("Các phần tử của OrderedDictionary1...");
foreach (DictionaryEntry d in dict1)
{
Console.WriteLine(d.Key + " " + d.Value);
}
OrderedDictionary dict2 = new OrderedDictionary();
dict2.Add("1", "One");
dict2.Add("2", "Two");
dict2.Add("3", "Three");
dict2.Add("4", "Four");
dict2.Add("5", "Five");
dict2.Add("6", "Six");
Console.WriteLine("\nCác phần tử của OrderedDictionary2...");
foreach (DictionaryEntry d in dict2)
{
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("\nOrderedDictionary1 có bằng OrderedDictionary2 không? = " + (dict1.Equals(dict2)));
}
}
Kết quả
Các phần tử của OrderedDictionary1... A Books B Electronics C Smart Wearables D Pet Supplies E Clothing F Footwear Các phần tử của OrderedDictionary2... 1 One 2 Two 3 Three 4 Four 5 Five 6 Six OrderedDictionary1 có bằng OrderedDictionary2 không? = False
Ví dụ 2: Gán tham chiếu
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
OrderedDictionary dict1 = new OrderedDictionary();
dict1.Add("A", "Books");
dict1.Add("B", "Electronics");
dict1.Add("C", "Smart Wearables");
dict1.Add("D", "Pet Supplies");
dict1.Add("E", "Clothing");
dict1.Add("F", "Footwear");
Console.WriteLine("Các phần tử của OrderedDictionary1...");
foreach (DictionaryEntry d in dict1)
{
Console.WriteLine(d.Key + " " + d.Value);
}
OrderedDictionary dict2 = new OrderedDictionary();
dict2.Add("1", "One");
dict2.Add("2", "Two");
dict2.Add("3", "Three");
dict2.Add("4", "Four");
dict2.Add("5", "Five");
dict2.Add("6", "Six");
Console.WriteLine("\nCác phần tử của OrderedDictionary2...");
foreach (DictionaryEntry d in dict2)
{
Console.WriteLine(d.Key + " " + d.Value);
}
OrderedDictionary dict3 = new OrderedDictionary();
dict3 = dict2; // Gán tham chiếu
Console.WriteLine("\nOrderedDictionary3 có bằng OrderedDictionary2 không? = " + (dict3.Equals(dict2)));
}
}
Kết quả
Các phần tử của OrderedDictionary1... A Books B Electronics C Smart Wearables D Pet Supplies E Clothing F Footwear Các phần tử của OrderedDictionary2... 1 One 2 Two 3 Three 4 Four 5 Five 6 Six OrderedDictionary3 có bằng OrderedDictionary2 không? = True
Lưu ý quan trọng: OrderedDictionary.Equals() so sánh tham chiếu. Hai OrderedDictionary khác instance nhưng có cùng khóa, giá trị, thứ tự sẽ trả về false. Để so sánh nội dung, hãy duyệt và so sánh từng cặp.