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

การดึงคอลเลกชันค่า (Values) จาก OrderedDictionary ใน C#


คุณสมบัติ OrderedDictionary.Values ใน C# ใช้สำหรับดึงคอลเลกชันของค่า (Values) ทั้งหมดใน OrderedDictionary คืนค่า ICollection ที่สามารถวนลูปหรือคัดลอกไปอาร์เรย์ได้

ตัวอย่างที่ 1: ดึง Values และคัดลอกไปอาร์เรย์สตริง

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.Values;
        string[] strVal = new string[dict.Count];
        col.CopyTo(strVal, 0);

        Console.WriteLine("Displaying the values...");
        for (int i = 0; i < dict.Count; i++)
        {
            Console.WriteLine(strVal[i]);
        }
    }
}

ผลลัพธ์

Displaying the values...
One
Two
Three
Four
Five
Six
Seven
Eight

ตัวอย่างที่ 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.Values;
        string[] strVal = new string[dict.Count];
        col.CopyTo(strVal, 0);

        Console.WriteLine("Displaying the Values...");
        for (int i = 0; i < dict.Count; i++)
        {
            Console.WriteLine(strVal[i]);
        }
    }
}

ผลลัพธ์

Displaying the Values...
John
Tim
Katie
Andy
Gary
Amy

ข้อสังเกตสำคัญ

  • OrderedDictionary (ใน System.Collections.Specialized) รักษาลำดับการเพิ่ม (insertion order) — ต่างจาก Hashtable/Dictionary
  • Values คืน ICollection — ไม่ได้คืนอาร์เรย์โดยตรง ต้องคัดลอกด้วย CopyTo() หรือใช้ foreach
  • สามารถใช้ foreach (var val in dict.Values) ได้โดยตรง
  • มี Keys property ให้เหมือนกันสำหรับดึงคอลเลกชัน Key
  • ใน .NET ใหม่ๆ แนะนำให้ใช้ Dictionary<TKey, TValue> (ไม่รับประกันลำดับ) หรือ SortedDictionary<TKey, TValue> (เรียงตาม Key) — OrderedDictionary เป็น legacy non-generic