Giới thiệu
Để xóa một cặp khóa/giá trị khỏi OrderedDictionary dựa trên khóa, bạn sử dụng phương thức Remove(key). Khác với RemoveAt(index) xóa theo vị trí, Remove(key) xóa theo khóa. Thứ tự các phần tử còn lại được bảo toàn.
Ví dụ 1: Xóa khóa "E"
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
OrderedDictionary dict = new OrderedDictionary();
dict.Add("A", "Books");
dict.Add("B", "Electronics");
dict.Add("C", "Smart Wearables");
dict.Add("D", "Pet Supplies");
dict.Add("E", "Clothing");
dict.Add("F", "Footwear");
Console.WriteLine("Các phần tử của OrderedDictionary...");
foreach (DictionaryEntry d in dict)
{
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("Số lượng phần tử trong OrderedDictionary = " + dict.Count);
dict.Remove("E");
Console.WriteLine("Số lượng phần tử trong OrderedDictionary (Đã cập nhật) = " + dict.Count);
}
}
Kết quả
Các phần tử của OrderedDictionary... A Books B Electronics C Smart Wearables D Pet Supplies E Clothing F Footwear Số lượng phần tử trong OrderedDictionary = 6 Số lượng phần tử trong OrderedDictionary (Đã cập nhật) = 5
Ví dụ 2: Xóa khóa "C" và "D"
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
OrderedDictionary dict = new OrderedDictionary();
dict.Add("A", "One");
dict.Add("B", "Two");
dict.Add("C", "Three");
dict.Add("D", "Four");
Console.WriteLine("Các phần tử của OrderedDictionary...");
foreach (DictionaryEntry d in dict)
{
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("Số lượng phần tử trong OrderedDictionary = " + dict.Count);
dict.Remove("C");
dict.Remove("D");
Console.WriteLine("Số lượng phần tử trong OrderedDictionary (Đã cập nhật) = " + dict.Count);
}
}
Kết quả
Các phần tử của OrderedDictionary... A One B Two C Three D Four Số lượng phần tử trong OrderedDictionary = 4 Số lượng phần tử trong OrderedDictionary (Đã cập nhật) = 2
Lưu ý: OrderedDictionary duy trì thứ tự chèn. Xóa theo khóa không làm thay đổi thứ tự các phần tử còn lại. Nếu khóa không tồn tại, không có lỗi xảy ra.