Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Sắp xếp List Dictionary theo giá trị trong C#


Để sắp xếp Dictionary theo giá trị (value) trong C#, có thể lấy keys, sắp xếp keys dựa trên values tương ứng.

Ví dụ

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

class Demo
{
    static void Main()
    {
        var dict = new Dictionary();
        dict.Add("Zack", 0);
        dict.Add("Akon", 3);
        dict.Add("Jack", 2);
        dict.Add("Tom", 1);
        
        // Cách 1: Sắp xếp keys theo values (giảm dần)
        var sortedKeys = dict.OrderByDescending(kvp => kvp.Value).Select(kvp => kvp.Key).ToList();
        
        Console.WriteLine("Sắp xếp theo giá trị giảm dần:");
        foreach (var key in sortedKeys)
            Console.WriteLine("{0}: {1}", key, dict[key]);
        
        // Cách 2: Sắp xếp toàn bộ KeyValuePair
        var sortedDict = dict.OrderByDescending(kvp => kvp.Value);
        
        Console.WriteLine("\nSắp xếp KeyValuePair:");
        foreach (var kvp in sortedDict)
            Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value);
    }
}

Kết quả

Sắp xếp theo giá trị giảm dần:
Akon: 3
Jack: 2
Tom: 1
Zack: 0

Sắp xếp KeyValuePair:
Akon: 3
Jack: 2
Tom: 1
Zack: 0

Giải thích

  • OrderByDescending(kvp => kvp.Value): Sắp xếp theo Value giảm dần
  • OrderBy(kvp => kvp.Value): Tăng dần
  • Kết quả là IOrderedEnumerable<KeyValuePair<TKey, TValue>>

Tạo Dictionary mới đã sắp xếp (C# 7.3+)

var sortedDict = dict.OrderByDescending(kvp => kvp.Value)
                     .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

Lưu ý: Dictionary gốc không giữ thứ tự (trước .NET Core 3.0). Dùng SortedDictionary hoặc SortedList nếu cần tự động sắp xếp theo Key.