Giới thiệu
Thuộc tính Dictionary<TKey, TValue>.Keys trả về KeyCollection. Để có List<TKey>, dùng constructor new List<TKey>(dict.Keys) hoặc LINQ dict.Keys.ToList().
Ví dụ cơ bản
Dictionaryd = new Dictionary { {1, "One"}, {2, "Two"}, {3, "Three"}, {4, "Four"}, {5, "Five"}, {6, "Six"}, {7, "Seven"}, {8, "Eight"} }; List keys = new List (d.Keys);
Ví dụ hoàn chỉnh
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Dictionary d = new Dictionary
{
{1, "One"}, {2, "Two"}, {3, "Three"}, {4, "Four"},
{5, "Five"}, {6, "Six"}, {7, "Seven"}, {8, "Eight"}
};
List keys = new List(d.Keys);
Console.WriteLine("Displaying keys...");
foreach (int res in keys) Console.WriteLine(res);
}
}
Kết quả
Displaying keys... 1 2 3 4 5 6 7 8
Các cách lấy Keys khác
var keys = dict.Keys.ToList();(LINQ, cầnusing System.Linq;)foreach (var key in dict.Keys) { ... }(duyệt trực tiếp, không cấp phát List)var keys = dict.Select(kvp => kvp.Key).ToList();(LINQ select)
Lưu ý
Keyslà view động: thay đổi Dictionary sẽ phản ánh trong Keys (nếu chưa ToList).- Thứ tự keys không đảm bảo (trừ
SortedDictionaryhoặc .NET Core 3.0+ Dictionary bảo toàn thứ tự chèn). - Không thể sửa đổi Keys collection trực tiếp (read-only).
Lấy Values tương tự
Listvalues = new List (d.Values); // hoặc var values = d.Values.ToList();