Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

จัดเรียงลิสต์ของ Dictionary ตามค่าใน C#

การเรียงลำดับ Dictionary ตามค่า (Value) ใน C#

ใน C# เราสามารถเรียงลำดับ Dictionary<TKey, TValue> ตามค่า (Value) ได้โดยใช้ LINQ ด้วยคำสั่ง orderby ตัวอย่างต่อไปนี้แสดงวิธีการสร้าง Dictionary เพิ่มข้อมูล และเรียงลำดับจากน้อยไปมาก (Ascending) หรือมากไปน้อย (Descending)

ตัวอย่างโค้ด

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // 1. สร้าง Dictionary
        var dict = new Dictionary<string, int>(5);

        // 2. เพิ่มคีย์และค่า
        dict.Add("car", 25);
        dict.Add("bus", 28);
        dict.Add("motorbike", 17);

        // 3. เรียงลำดับตาม Value (Ascending)
        var sorted = from entry in dict
                     orderby entry.Value ascending
                     select entry;

        // 4. แสดงผลลัพธ์
        foreach (var pair in sorted)
        {
            Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
        }
    }
}

ผลลัพธ์

motorbike = 17
car = 25
bus = 28

คำอธิบายเพิ่มเติม

  • ใช้ orderby entry.Value descending หากต้องการเรียงจากมากไปน้อย
  • สามารถใช้ Lambda Syntax ได้เช่นกัน: var sorted = dict.OrderBy(x => x.Value);
  • ผลลัพธ์ที่ได้คือ IEnumerable<KeyValuePair<string, int>> ไม่ใช่ Dictionary ใหม่ หากต้องการ Dictionary ใหม่ให้ใช้ .ToDictionary(x => x.Key, x => x.Value)