การเรียงลำดับ Dictionary ตาม Key ใน C#
สำคัญ: C# ไม่มี HashMap (เป็นของ Java) คลาสที่เทียบเท่าคือ Dictionary<TKey, TValue> ซึ่ง ไม่รับประกันลำดับ หากต้องการเรียงลำดับต้องแปลงเป็น List หรือใช้ SortedDictionary
วิธีที่ 1: เรียง Key แล้ววนลูป (Simple)
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
var dict = new Dictionary
{
["soccer"] = 1,
["cricket"] = 2,
["tennis"] = 3,
["rugby"] = 4
};
// ดึง Keys เรียงลำดับ
var sortedKeys = dict.Keys.OrderBy(k => k).ToList();
// หรือ
// var sortedKeys = new List(dict.Keys);
// sortedKeys.Sort();
Console.WriteLine("Keys เรียงลำดับ:");
foreach (var key in sortedKeys)
{
Console.WriteLine($"{key}: {dict[key]}");
}
}
}
ผลลัพธ์
Keys เรียงลำดับ:
cricket: 2
rugby: 4
soccer: 1
tennis: 3
วิธีที่ 2: ใช้ SortedDictionary (Auto-sorted)
using System;
using System.Collections.Generic;
var sortedDict = new SortedDictionary
{
["soccer"] = 1,
["cricket"] = 2,
["tennis"] = 3,
["rugby"] = 4
};
// เรียงอัตโนมัติตาม Key
foreach (var kvp in sortedDict)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
วิธีที่ 3: LINQ OrderBy (ยืดหยุ่นมากที่สุด)
using System.Linq;
// เรียงตาม Key
var byKey = dict.OrderBy(kvp => kvp.Key);
// เรียงตาม Value
var byValue = dict.OrderBy(kvp => kvp.Value);
// เรียง Key แล้ว Value
var byKeyThenValue = dict.OrderBy(kvp => kvp.Key).ThenBy(kvp => kvp.Value);
// เรียงย้อนกลับ
var descending = dict.OrderByDescending(kvp => kvp.Value);
// สร้าง Dictionary ใหม่ (C# 7.0+)
var newDict = dict.OrderBy(kvp => kvp.Key).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
ตัวอย่างครบ: เรียงตาม Value (คะแนน)
var scores = new Dictionary
{
["Alice"] = 85,
["Bob"] = 92,
["Charlie"] = 78,
["Diana"] = 96
};
Console.WriteLine("เรียงตามคะแนน (มากไปน้อย):");
foreach (var kvp in scores.OrderByDescending(k => k.Value))
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
ผลลัพธ์
เรียงตามคะแนน (มากไปน้อย):
Diana: 96
Bob: 92
Alice: 85
Charlie: 78
เปรียบเทียบ Dictionary Types
| Type | ลำดับ | Key Unique | Performance | Thread-Safe |
|---|---|---|---|---|
Dictionary<TKey,TValue> | ไม่รับประกัน | ใช่ | O(1) เร็วที่สุด | ไม่ |
SortedDictionary<TKey,TValue> | เรียง Key (BST) | ใช่ | O(log n) | ไม่ |
SortedList<TKey,TValue> | เรียง Key (Array) | ใช่ | O(log n) ค้นหา, O(n) เพิ่ม/ลบ | ไม่ |
ConcurrentDictionary<TKey,TValue> | ไม่รับประกัน | ใช่ | O(1) ~ O(log n) | ใช่ |
ข้อควรระวัง
Dictionaryไม่รักษาลำดับการเพิ่ม (Insertion order) - ใช้OrderedDictionary(non-generic) ถ้าต้องการ- Key ต้อง implement
IComparableหรือมีIComparerสำหรับ SortedDictionary - หาก Key เป็น reference type ต้อง override Equals/GetHashCode ให้ถูกต้อง