c#

C#字典的键值对如何排序

小樊
81
2024-09-11 10:23:38
栏目: 编程语言

在C#中,字典(Dictionary)是一种无序的集合,它不保证元素的顺序。如果你需要对字典的键值对进行排序,可以使用以下方法:

  1. 使用OrderByThenBy方法对字典进行排序:
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. 将字典转换为有序集合,例如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 对键进行排序
        SortedDictionary<string, int> sortedDictByKey = new SortedDictionary<string, int>(dict);

        // 使用 SortedList 对值进行排序
        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}");
        }
    }
}

请注意,这些方法会创建新的集合,而不是修改原始字典。如果你需要保留原始字典的顺序,可以使用这些方法之一。如果你不关心原始字典的顺序,可以直接对其进行排序。

0
看了该问题的人还看了