溫馨提示×

C#字典的鍵值對如何排序

c#
小樊
81
2024-09-11 10:23:38
欄目: 編程語言

在C#中,字典(Dictionary)是一種無序的集合,它不保證元素的順序。如果你需要對字典的鍵值對進(jìn)行排序,可以使用以下方法:

  1. 使用OrderByThenBy方法對字典進(jìn)行排序:
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        Dictionary<string, int> dict = new Dictionary<string, int>
        {
            {"apple", 5},
            {"banana", 3},
            {"orange", 7},
            {"grape", 2}
        };

        // 按鍵(Key)排序
        var sortedByKey = dict.OrderBy(x => x.Key);

        // 按值(Value)排序
        var sortedByValue = dict.OrderBy(x => x.Value);

        Console.WriteLine("Sorted by Key:");
        foreach (var item in sortedByKey)
        {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }

        Console.WriteLine("\nSorted by Value:");
        foreach (var item in sortedByValue)
        {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}
  1. 將字典轉(zhuǎn)換為有序集合,例如SortedDictionarySortedList
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> dict = new Dictionary<string, int>
        {
            {"apple", 5},
            {"banana", 3},
            {"orange", 7},
            {"grape", 2}
        };

        // 使用 SortedDictionary 對鍵進(jìn)行排序
        SortedDictionary<string, int> sortedDictByKey = new SortedDictionary<string, int>(dict);

        // 使用 SortedList 對值進(jìn)行排序
        SortedList<int, string> sortedListByValue = new SortedList<int, string>();
        foreach (var item in dict)
        {
            sortedListByValue.Add(item.Value, item.Key);
        }

        Console.WriteLine("Sorted by Key using SortedDictionary:");
        foreach (var item in sortedDictByKey)
        {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }

        Console.WriteLine("\nSorted by Value using SortedList:");
        foreach (var item in sortedListByValue)
        {
            Console.WriteLine($"{item.Value}: {item.Key}");
        }
    }
}

請注意,這些方法會創(chuàng)建新的集合,而不是修改原始字典。如果你需要保留原始字典的順序,可以使用這些方法之一。如果你不關(guān)心原始字典的順序,可以直接對其進(jìn)行排序。

0