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

ดึง ICollection ที่มีคีย์ใน OrderedDictionary ใน C#

ภาพรวม

OrderedDictionary ใน namespace System.Collections.Specialized เป็นดิกชันนารีที่รักษาลำดับการเพิ่ม (insertion order) คุณสมบัติ Keys คืนค่า ICollection ของคีย์ทั้งหมดตามลำดับที่เพิ่ม

ตัวอย่างที่ 1: ดึงคีย์และแสดงด้วย CopyTo

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

public class Demo
{
    public static void Main()
    {
        OrderedDictionary dict = new OrderedDictionary();
        dict.Add("1", "One");
        dict.Add("2", "Two");
        dict.Add("3", "Three");
        dict.Add("4", "Four");
        dict.Add("5", "Five");
        dict.Add("6", "Six");
        dict.Add("7", "Seven");
        dict.Add("8", "Eight");
        ICollection col = dict.Keys;
        String[] strKeys = new String[dict.Count];
        col.CopyTo(strKeys, 0);
        Console.WriteLine("Displaying the keys...");
        for (int i = 0; i < dict.Count; i++)
        {
            Console.WriteLine(strKeys[i]);
        }
    }
}

ผลลัพธ์

Displaying the keys...
1
2
3
4
5
6
7
8

ตัวอย่างที่ 2: ดึงคีย์จาก OrderedDictionary อีกตัว

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

public class Demo
{
    public static void Main()
    {
        OrderedDictionary dict = new OrderedDictionary();
        dict.Add("One", "John");
        dict.Add("Two", "Tim");
        dict.Add("Three", "Katie");
        dict.Add("Four", "Andy");
        dict.Add("Five", "Gary");
        dict.Add("Six", "Amy");
        ICollection col = dict.Keys;
        String[] strKeys = new String[dict.Count];
        col.CopyTo(strKeys, 0);
        Console.WriteLine("Displaying the keys...");
        for (int i = 0; i < dict.Count; i++)
        {
            Console.WriteLine(strKeys[i]);
        }
    }
}

ผลลัพธ์

Displaying the keys...
One
Two
Three
Four
Five
Six

คำอธิบายเพิ่มเติม

  • Keys คืนค่า ICollection ที่เป็นมุมมอง (view) ของคีย์ ลำดับตรงกับการเพิ่ม
  • CopyTo(Array, index) คัดลอกคีย์ไปยังอาร์เรย์เริ่มจากดัชนีที่ระบุ
  • OrderedDictionary ใช้ Hashtable + ArrayList ภายใน ให้ O(1) สำหรับค้นหาด้วยคีย์ และรักษาลำดับ
  • คีย์ต้องเป็น unique (ไม่ซ้ำ) คีย์ซ้ำจะโยน ArgumentException
  • สำหรับโค้ดใหม่ พิจารณา Dictionary<TKey, TValue> + รายการคีย์แยก หรือ OrderedDictionary<TKey, TValue> (third-party)