C# không có Map built-in, dùng Dictionary<TKey, TValue>.
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("keyboard", 1);
d.Add("mouse", 2);
Lấy keys, sort, duyệt:
var keys = d.Keys.ToList(); keys.Sort(); foreach (var key in keys) Console.WriteLine(key);
Ví dụ
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
var d = new Dictionary<string, int>();
d.Add("keyboard", 1);
d.Add("mouse", 2);
var keys = d.Keys.ToList();
keys.Sort();
foreach (var key in keys)
Console.WriteLine(key);
}
}
Kết quả
keyboard mouse
Cách ngắn gọn LINQ:
foreach (var kvp in d.OrderBy(k => k.Key))
Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value);
SortedDictionary: Tự động sort theo key: var sd = new SortedDictionary<string, int>(d);