Giới thiệu
OrderedDictionary.Insert(int index, object key, object value) chèn cặp key-value tại vị trí index. Key phải duy nhất, index trong [0, Count].
Ví dụ 1: Insert tại index 7 (giữa)
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
OrderedDictionary dict = new OrderedDictionary();
for (int i = 1; i <= 8; i++)
dict.Add(i.ToString(), i.ToString()); // "1"->"1", ..., "8"->"8"
Console.WriteLine("Ban đầu:");
IDictionaryEnumerator enumr = dict.GetEnumerator();
while (enumr.MoveNext())
Console.WriteLine($"Key = {enumr.Key}, Value = {enumr.Value}");
// Chèn "15"->"Fifteen" tại index 7 (trước "8")
dict.Insert(7, "15", "Fifteen");
Console.WriteLine("\nSau Insert(7, '15', 'Fifteen'):");
enumr = dict.GetEnumerator();
while (enumr.MoveNext())
Console.WriteLine($"Key = {enumr.Key}, Value = {enumr.Value}");
}
}
Kết quả
Ban đầu:
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five
Key = 6, Value = Six
Key = 7, Value = Seven
Key = 8, Value = Eight
Sau Insert(7, '15', 'Fifteen'):
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five
Key = 6, Value = Six
Key = 7, Value = Seven
Key = 15, Value = Fifteen
Key = 8, Value = Eight
Ví dụ 2: Insert sau khi Add thêm
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
OrderedDictionary dict = new OrderedDictionary();
dict.Add("A", "Laptop");
dict.Add("B", "Desktop");
Console.WriteLine("Ban đầu:");
PrintDict(dict);
dict.Add("C", "Ultrabook");
dict.Add("D", "Alienware");
Console.WriteLine("\nSau Add C, D:");
PrintDict(dict);
// Chèn "K"->"Speakers" tại index 2 (trước "C")
dict.Insert(2, "K", "Speakers");
Console.WriteLine("\nSau Insert(2, 'K', 'Speakers'):");
PrintDict(dict);
}
static void PrintDict(OrderedDictionary dict)
{
IDictionaryEnumerator e = dict.GetEnumerator();
while (e.MoveNext())
Console.WriteLine($"Key = {e.Key}, Value = {e.Value}");
}
}
Kết quả
Ban đầu:
Key = A, Value = Laptop
Key = B, Value = Desktop
Sau Add C, D:
Key = A, Value = Laptop
Key = B, Value = Desktop
Key = C, Value = Ultrabook
Key = D, Value = Alienware
Sau Insert(2, 'K', 'Speakers'):
Key = A, Value = Laptop
Key = B, Value = Desktop
Key = K, Value = Speakers
Key = C, Value = Ultrabook
Key = D, Value = Alienware
Lưu ý quan trọng
- Key **phải duy nhất**. Ném
ArgumentExceptionnếu trùng. index= Count -> tương đươngAdd.OrderedDictionarylà non-generic (legacy). Code mới nên dùngDictionary<TKey, TValue>+ list key, hoặc thư việnOrderedDictionary<TKey, TValue>(NuGet).- Không thread-safe.