Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# dictionary 排序

作者:青灯寂焚   发布日期:2025-12-06   浏览:66

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 创建一个 Dictionary 并添加一些键值对
        Dictionary<string, int> dictionary = new Dictionary<string, int>
        {
            {"apple", 1},
            {"banana", 2},
            {"cherry", 3},
            {"date", 4}
        };

        // 按键排序
        var sortedByKey = new SortedDictionary<string, int>(dictionary);
        Console.WriteLine("Sorted by Key:");
        foreach (var item in sortedByKey)
        {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }

        // 按值排序
        var sortedByValue = dictionary.OrderBy(pair => pair.Value).ToDictionary(pair => pair.Key, pair => pair.Value);
        Console.WriteLine("\nSorted by Value:");
        foreach (var item in sortedByValue)
        {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}

解释说明:

  1. 创建 Dictionary:首先,我们创建了一个 Dictionary<string, int> 并添加了一些键值对。
  2. 按键排序:使用 SortedDictionary 可以直接按键进行排序。SortedDictionary 是一个有序的字典,它会根据键的自然顺序进行排序。
  3. 按值排序:使用 LINQ 的 OrderBy 方法可以按值进行排序。OrderBy 返回一个 IEnumerable<KeyValuePair<string, int>>,然后我们使用 ToDictionary 将其转换回字典。

这段代码展示了如何按键和按值对 Dictionary 进行排序,并打印出排序后的结果。

上一篇:c# 位运算

下一篇:c# fileinfo

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站