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

Sắp xếp KeyValuePair trong C#


Giới thiệu

Để sắp xếp một danh sách List<KeyValuePair<TKey, TValue>>, sử dụng phương thức Sort() với một delegate so sánh (comparison delegate).

Ví dụ cơ bản

Khởi tạo danh sách:

var myList = new List>();
myList.Add(new KeyValuePair(1, 20));
myList.Add(new KeyValuePair(2, 15));
myList.Add(new KeyValuePair(3, 35));
myList.Add(new KeyValuePair(4, 50));
myList.Add(new KeyValuePair(5, 25));

Sắp xếp giảm dần theo Value:

myList.Sort((x, y) => y.Value.CompareTo(x.Value));

Ví dụ hoàn chỉnh

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var myList = new List>();
        myList.Add(new KeyValuePair(1, 20));
        myList.Add(new KeyValuePair(2, 15));
        myList.Add(new KeyValuePair(3, 35));
        myList.Add(new KeyValuePair(4, 50));
        myList.Add(new KeyValuePair(5, 25));

        Console.WriteLine("Danh sách chưa sắp xếp...");
        foreach (var val in myList)
        {
            Console.WriteLine(val);
        }

        // Sắp xếp giảm dần theo Value
        myList.Sort((x, y) => y.Value.CompareTo(x.Value));

        Console.WriteLine("Danh sách đã sắp xếp...");
        foreach (var val in myList)
        {
            Console.WriteLine(val);
        }
    }
}

Kết quả

Danh sách chưa sắp xếp...
[1, 20]
[2, 15]
[3, 35]
[4, 50]
[5, 25]
Danh sách đã sắp xếp...
[4, 50]
[3, 35]
[5, 25]
[1, 20]
[2, 15]

Các cách sắp xếp khác

  • Tăng dần theo Value: myList.Sort((x, y) => x.Value.CompareTo(y.Value));
  • Giảm dần theo Key: myList.Sort((x, y) => y.Key.CompareTo(x.Key));
  • Sắp xếp phức tạp: Dùng Comparer<KeyValuePair<TKey, TValue>>.Create() hoặc implement IComparer.

Lưu ý

  • Sort() sắp xếp tại chỗ (in-place), thay đổi thứ tự của list gốc.
  • Nếu không muốn sửa đổi list gốc, dùng LINQ: var sorted = myList.OrderByDescending(x => x.Value).ToList();
  • Delegate so sánh phải trả về: < 0 (x < y), 0 (x = y), > 0 (x > y).