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

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

ภาพรวม

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

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

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

public class Demo
{
    public static void Main()
    {
        StringDictionary strDict = new StringDictionary();
        strDict.Add("1", "SUV");
        strDict.Add("2", "AUV");
        strDict.Add("3", "Electric Car");
        strDict.Add("4", "Utility Vehicle");
        strDict.Add("5", "Hatchback");
        strDict.Add("6", "Compact car");
        strDict.Add("7", "MUV");
        strDict.Add("8", "Crossover");
        strDict.Add("9", "Covertible");
        strDict.Add("10", "Quadricycle");

        DictionaryEntry[] arr = { new DictionaryEntry(),
            new DictionaryEntry(),
            new DictionaryEntry(),
            new DictionaryEntry(),
            new DictionaryEntry(),
            new DictionaryEntry(),
            new DictionaryEntry(),
            new DictionaryEntry(),
            new DictionaryEntry(),
            new DictionaryEntry() };

        strDict.CopyTo(arr, 0);

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

ผลลัพธ์

10 Quadricycle
1 SUV
2 AUV
3 Electric Car
4 Utility Vehicle
5 Hatchback
6 Compact car
7 MUV
8 Crossover
9 Covertible

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

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

public class Demo
{
    public static void Main()
    {
        StringDictionary strDict = new StringDictionary();
        strDict.Add("1", "SUV");
        strDict.Add("2", "AUV");
        strDict.Add("3", "Electric Car");
        strDict.Add("4", "Utility Vehicle");
        strDict.Add("5", "Hatchback");
        strDict.Add("6", "Compact car");

        DictionaryEntry[] arr = { new DictionaryEntry(),
            new DictionaryEntry(),
            new DictionaryEntry(),
            new DictionaryEntry(),
            new DictionaryEntry(),
            new DictionaryEntry(),
            new DictionaryEntry(),
            new DictionaryEntry() };

        strDict.CopyTo(arr, 2);

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

ผลลัพธ์

1 SUV
2 AUV
3 Electric Car
4 Utility Vehicle
5 Hatchback
6 Compact car

สรุป

  • StringDictionary เก็บคีย์และค่าเป็นสตริง (ไม่จัดเรียง)
  • CopyTo ต้องการอาร์เรย์ DictionaryEntry[]
  • ลำดับข้อมูลขึ้นอยู่กับการจัดเก็บภายใน (ไม่ได้รับประกัน)