บทความนี้สาธิตวิธีการดึง ICollection ที่มีคีย์ (keys) ทั้งหมดจาก ListDictionary ใน C# โดยใช้ property Keys และวนลูปด้วย 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 col = listDict.Keys;
foreach (String s in col)
{
Console.WriteLine(s);
}
}
}
ผลลัพธ์
1 2 3 4 5 6
ตัวอย่างที่ 2: ตัวอย่างเพิ่มเติม
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.Keys;
foreach (String s in col)
{
Console.WriteLine(s);
}
}
}
ผลลัพธ์
A B C D
คำอธิบายเพิ่มเติม
ListDictionaryเหมาะสำหรับจำนวนข้อมูลน้อย (น้อยกว่า 10 รายการ) ใช้ linked list ในการจัดเก็บ- Property
Keysคืนค่าICollectionที่มีคีย์ทั้งหมด - ลำดับของคีย์จะตรงกับลำดับที่เพิ่มเข้าไป (maintains insertion order)
- ใช้
foreachวนลูปผ่าน ICollection ได้โดยตรง