[C#] 如何对列表,字典等进行排序?

对列表进行排序

下面是一个基于C#的列表排序的案例:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // 创建一个列表
        List<int> numbers = new List<int>() { 5, 2, 8, 1, 10 };

        // 使用Sort方法对列表进行升序排序
        numbers.Sort();

        // 打印排序后的列表
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }

        // 使用Reverse方法对列表进行降序排序
        numbers.Reverse();

        // 打印排序后的列表
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

这个案例演示了对一个整数列表进行排序的过程。首先,使用Sort方法对列表进行升序排序,然后遍历列表并打印排序后的结果。接着,使用Reverse方法对列表进行降序排序,并再次遍历并打印结果。

输出结果:

1
2
5
8
10
10
8
5
2
1

对字典进行排序

在C#中,可以使用OrderBy方法对字典进行排序。下面是一个对字典按键值进行升序排序的示例:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        Dictionary<string, int> dictionary = new Dictionary<string, int>();
        dictionary.Add("apple", 2);
        dictionary.Add("banana", 1);
        dictionary.Add("orange", 3);

        var sortedDictionary = dictionary.OrderBy(x => x.Key);

        foreach (var item in sortedDictionary)
        {
            Console.WriteLine(item.Key + ": " + item.Value);
        }
    }
}

输出结果:apple: 2
banana: 1
orange: 3

如果要根据值进行排序,可以将OrderBy的委托参数改为x => x.Value

最近更新

  1. TCP协议是安全的吗?

    2024-02-11 12:38:03       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-11 12:38:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-11 12:38:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-11 12:38:03       20 阅读

热门阅读

  1. 【Linux】基于单例模式懒汉实现方式的线程池

    2024-02-11 12:38:03       26 阅读
  2. Shell之sed

    2024-02-11 12:38:03       33 阅读
  3. 【算法】【数据结构】算法与数据结构的关系

    2024-02-11 12:38:03       33 阅读
  4. mysql

    mysql

    2024-02-11 12:38:03      29 阅读
  5. Nginx配置php留档

    2024-02-11 12:38:03       28 阅读
  6. RuoYi模块功能分析:第八章定时任务

    2024-02-11 12:38:03       26 阅读
  7. P2036 [COCI2008-2009 #2] PERKET题解

    2024-02-11 12:38:03       28 阅读
  8. 学习数据结构和算法的第6天

    2024-02-11 12:38:03       28 阅读
  9. 设计模式-适配器模式 Adapter

    2024-02-11 12:38:03       28 阅读
  10. 应急响应-挖矿木马-常规处置方法

    2024-02-11 12:38:03       27 阅读
  11. 面试心得--面试前应该如何准备

    2024-02-11 12:38:03       21 阅读