如何在 C# 中使用数组类的 Sort() 方法?
csharpprogrammingserver side programming
Sort() 方法使用数组中每个元素的 IComparable 实现对整个一维数组中的元素进行排序。
设置数组。
int[] list = { 22, 12, 65, 9};
使用 Sort() 方法对数组进行排序。
Array.Sort(list);
以下示例用于学习如何使用 Sort() 方法。
示例
using System; namespace Demo { class Program { static void Main(string[] args) { int[] list = { 22, 12, 65, 9}; Console.Write("原始数组: "); foreach (int i in list) { Console.Write(i + " "); } Console.WriteLine(); //对数组进行排序 Array.Sort(list); Console.Write("排序后的数组:"); foreach (int i in list) { Console.Write(i + " "); } Console.WriteLine(); Console.ReadKey(); } } }
输出
原始数组:22 12 65 9 排序后的数组:9 12 22 65