Giới thiệu
Để lấy một ICollection chứa các khóa trong ListDictionary, bạn có thể truy cập trực tiếp thuộc tính Keys. Dưới đây là các ví dụ minh họa.
Ví dụ 1
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);
}
}
}
Kết quả
1 2 3 4 5 6
Ví dụ 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);
}
}
}
Kết quả
A B C D
Lưu ý: ListDictionary duy trì thứ tự thêm vào, do đó các khóa sẽ được trả về theo thứ tự đó.