Dictionary<TKey, TValue> duyệt qua Keys, Values, hoặc KeyValuePair.
Cách 1: Duyệt Keys (cũ)
IDictionary<int, int> d = new Dictionary<int, int>();
d.Add(1, 97); d.Add(2, 89); d.Add(3, 77); d.Add(4, 88);
List<int> keys = new List<int>(d.Keys);
foreach (int k in keys) Console.WriteLine("{0}, {1}", k, d[k]);
Cách 2: foreach trực tiếp (khuyến nghị)
foreach (var kvp in d)
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
Cách 3: Chỉ Values
foreach (int v in d.Values) Console.WriteLine(v);
Ví dụ hoàn chỉnh
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
var d = new Dictionary<int, int>();
d.Add(1, 97); d.Add(2, 89); d.Add(3, 77); d.Add(4, 88);
foreach (var kvp in d)
Console.WriteLine("{0}, {1}", kvp.Key, kvp.Value);
}
}
Kết quả
1, 97 2, 89 3, 77 4, 88
Lưu ý: Thứ tự Dictionary không đảm bảo (trước .NET Core 3.0). Dùng SortedDictionary hoặc OrderedDictionary nếu cần thứ tự. Không sửa đổi dictionary trong foreach.