对列表进行排序
下面是一个基于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
。