Trong C#, Dictionary<TKey, TValue> không duy trì thứ tự các phần tử. Để sắp xếp theo giá trị (value), chúng ta sử dụng LINQ với mệnh đề orderby.
Ví dụ minh họa
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Khởi tạo Dictionary
var d = new Dictionary<string, int>(5);
// Thêm cặp key-value
d.Add("car", 25);
d.Add("bus", 28);
d.Add("motorbike", 17);
// Sắp xếp theo giá trị tăng dần (ascending)
var val = from ele in d
orderby ele.Value ascending
select ele;
// Hoặc dùng method syntax:
// var val = d.OrderBy(x => x.Value);
// Hiển thị kết quả
foreach (KeyValuePair<string, int> ele in val)
{
Console.WriteLine("{0} = {1}", ele.Key, ele.Value);
}
// Để sắp xếp giảm dần, dùng descending:
// var valDesc = from ele in d orderby ele.Value descending select ele;
}
}
Kết quả
motorbike = 17 car = 25 bus = 28
Giải thích
- Dictionary: Lưu trữ cặp khóa-giá trị, không cho phép khóa trùng lặp.
- LINQ query syntax:
from ... orderby ... selectcho phép sắp xếp linh hoạt. - Method syntax:
d.OrderBy(x => x.Value)ngắn gọn hơn, thường được ưu tiên. - KeyValuePair: Kiểu trả về khi duyệt Dictionary, chứa cả Key và Value.
Lưu ý: Kết quả sắp xếp là một IOrderedEnumerable, không phải Dictionary. Nếu cần Dictionary đã sắp xếp, hãy dùng .ToDictionary() (tuy nhiên Dictionary bản thân không bảo toàn thứ tự).