溫馨提示×

c# keyvaluepair如何排序

c#
小樊
129
2024-11-20 06:37:11
欄目: 編程語言

在C#中,您可以使用SortedSet<KeyValuePair<TKey, TValue>>SortedSet<T>來存儲鍵值對并自動對其進行排序。SortedSet是基于紅黑樹實現的,它會根據鍵或值的自然順序或者提供的比較器進行排序。

以下是一個使用SortedSet<KeyValuePair<TKey, TValue>>的示例:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 創建一個包含鍵值對的列表
        List<KeyValuePair<int, string>> keyValuePairs = new List<KeyValuePair<int, string>>
        {
            new KeyValuePair<int, string>(3, "three"),
            new KeyValuePair<int, string>(1, "one"),
            new KeyValuePair<int, string>(2, "two")
        };

        // 使用SortedSet存儲鍵值對并自動排序
        SortedSet<KeyValuePair<int, string>> sortedSet = new SortedSet<KeyValuePair<int, string>>(keyValuePairs);

        // 輸出排序后的鍵值對
        foreach (var item in sortedSet)
        {
            Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
        }
    }
}

如果您想根據值進行排序,可以使用SortedSet<T>并實現一個自定義比較器:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 創建一個包含鍵值對的列表
        List<KeyValuePair<int, string>> keyValuePairs = new List<KeyValuePair<int, string>>
        {
            new KeyValuePair<int, string>(3, "three"),
            new KeyValuePair<int, string>(1, "one"),
            new KeyValuePair<int, string>(2, "two")
        };

        // 使用SortedSet存儲鍵值對并自動根據值排序
        SortedSet<KeyValuePair<int, string>> sortedSet = new SortedSet<KeyValuePair<int, string>>(
            keyValuePairs,
            new Comparer<KeyValuePair<int, string>>(
                (x, y) => string.Compare(x.Value, y.Value)
            )
        );

        // 輸出排序后的鍵值對
        foreach (var item in sortedSet)
        {
            Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
        }
    }
}

這兩個示例都會輸出按值排序的鍵值對:

Key: 1, Value: one
Key: 2, Value: two
Key: 3, Value: three

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女