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

ดึงคอลเลกชันค่าจาก ListDictionary ใน C#

คุณสมบัติ Values ของ ListDictionary คืนค่า ICollection ที่มีค่าทั้งหมด (Values) สามารถวนลูปด้วย foreach หรือคัดลอกไปอาร์เรย์ได้

ตัวอย่างที่ 1: ดึงค่าทั้งหมดจาก ListDictionary

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

public class Demo
{
    public static void Main()
    {
        ListDictionary listDict = new ListDictionary();
        listDict.Add("1", "Laptop");
        listDict.Add("2", "Tablet");
        listDict.Add("3", "Desktop");
        listDict.Add("4", "Speaker");
        listDict.Add("5", "Earphone");
        listDict.Add("6", "Headphone");

        // ดึง ICollection ของค่า
        ICollection col = listDict.Values;

        // วนลูปแสดงค่าแต่ละตัว
        foreach (String s in col)
        {
            Console.WriteLine(s);
        }
    }
}

ผลลัพธ์

Laptop
Tablet
Desktop
Speaker
Earphone
Headphone

ตัวอย่างที่ 2: ListDictionary อื่น

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

public class Demo
{
    public static void Main()
    {
        ListDictionary listDict = new ListDictionary();
        listDict.Add("A", "Tom");
        listDict.Add("B", "John");
        listDict.Add("C", "Kevin");
        listDict.Add("D", "Tim");

        ICollection col = listDict.Values;

        foreach (String s in col)
        {
            Console.WriteLine(s);
        }
    }
}

ผลลัพธ์

Tom
John
Kevin
Tim

วิธีการอื่นๆ

// 1. คัดลอกไปอาร์เรย์
string[] valuesArray = new string[listDict.Count];
listDict.Values.CopyTo(valuesArray, 0);

// 2. ใช้ LINQ (ต้อง using System.Linq)
var valuesList = listDict.Values.Cast<string>().ToList();
valuesList.ForEach(v => Console.WriteLine(v));

// 3. วนลูปผ่าน Keys แล้วดึง Value (หากต้องการคีย์ด้วย)
foreach (var key in listDict.Keys)
{
    Console.WriteLine($"Key: {key}, Value: {listDict[key]}");
}

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

  • Values คืนค่า ICollection รองรับ Count, CopyTo, GetEnumerator
  • ลำดับของ Values ตรงกับลำดับของ Keys (แต่ ListDictionary ไม่รับประกันลำดับ)
  • ListDictionary เหมาะสำหรับข้อมูลน้อย (< 10 รายการ) ใช้ Linked List ภายใน
  • สำหรับโปรเจกต์ใหม่ แนะนำใช้ Dictionary<TKey, TValue> ซึ่งมี .Values คืนค่า ValueCollection<TValue> ที่ทรงพลังกว่า