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

对列表进行排序

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

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // 创建一个列表
        List numbers = new List() { 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 dictionary = new Dictionary();
        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

你可能感兴趣的:(C#,c#)