Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การคัดลอก OrderedDictionary ไปยังอาร์เรย์ที่ดัชนีที่กำหนดใน C#

ภาพรวม

OrderedDictionary.CopyTo(Array array, int index) คัดลอกคู่คีย์/ค่าเป็น DictionaryEntry ไปยังอาร์เรย์ เริ่มที่ดัชนีที่ระบุ ลำดับจะถูกเก็บรักษา

ตัวอย่างที่ 1: คัดลอก 5 คู่ไปอาร์เรย์ขนาด 5 เริ่มดัชนี 0

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        OrderedDictionary dict = new OrderedDictionary();
        dict.Add(1, "Harry");
        dict.Add(2, "Mark");
        dict.Add(3, "John");
        dict.Add(4, "Jacob");
        dict.Add(5, "Tim");

        Console.WriteLine("OrderedDictionary elements...");
        foreach (DictionaryEntry d in dict)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }

        DictionaryEntry[] dictArr = new DictionaryEntry[dict.Count];
        Console.WriteLine("\nCopying to Array instance...");
        dict.CopyTo(dictArr, 0);

        for (int i = 0; i < dictArr.Length; i++)
        {
            Console.WriteLine("Key = " + dictArr[i].Key + ", Value = " + dictArr[i].Value);
        }
    }
}

ผลลัพธ์

OrderedDictionary elements...
1 Harry
2 Mark
3 John
4 Jacob
5 Tim
Copying to Array instance...
Key = 5, Value = Tim
Key = 4, Value = Jacob
Key = 3, Value = John
Key = 2, Value = Mark
Key = 1, Value = Harry

ตัวอย่างที่ 2: คัดลอก 2 คู่ไปอาร์เรย์ขนาด 5 เริ่มดัชนี 0

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        OrderedDictionary dict = new OrderedDictionary();
        dict.Add(1, 10);
        dict.Add(2, 20);

        Console.WriteLine("OrderedDictionary elements...");
        foreach (DictionaryEntry d in dict)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }

        DictionaryEntry[] dictArr = new DictionaryEntry[5];
        Console.WriteLine("\nCopying to Array instance...");
        dict.CopyTo(dictArr, 0);

        for (int i = 0; i < dictArr.Length; i++)
        {
            Console.WriteLine("Key = " + dictArr[i].Key + ", Value = " + dictArr[i].Value);
        }
    }
}

ผลลัพธ์

OrderedDictionary elements...
1 10
2 20
Copying to Array instance...
Key = 2, Value = 20
Key = 1, Value = 10
Key = , Value = 
Key = , Value = 
Key = , Value = 

สรุป

  • OrderedDictionary รักษาลำดับการเพิ่มข้อมูล (insertion order)
  • CopyTo คัดลอกเป็น DictionaryEntry[] ต้องระบุขนาดอาร์เรย์
  • ลำดับในอาร์เรย์: เริ่มจากข้อมูลที่เพิ่มล่าสุด (reverse order)