c# 数组排序


在C#中,可以使用内置的排序方法对数组进行排序。以下是一些常用的排序方法:

使用Array.Sort<T>方法对数组进行排序。这是一个通用方法,可以对任何类型的数组进行排序,只要类型实现了IComparable接口。

int[] array = new int[] { 3, 1, 4, 1, 5, 9 };
Array.Sort(array);

  使用List<T>.Sort方法对列表进行排序。这是一个泛型版本的方法,它只能用于List<T>类型的数据,其中T是实现了IComparable接口的类型。

List<int> list = new List<int> { 3, 1, 4, 1, 5, 9 };
list.Sort();

  

  1. 使用Array.Sort<T, TKey>方法对数组进行排序,并指定一个键用来进行比较。

    var people = new[]
    {
        new { Name = "John", Age = 45 },
        new { Name = "Anne", Age = 32 },
        new { Name = "Bill", Age = 27 }
    };
     
    Array.Sort(people, (p1, p2) => p1.Age.CompareTo(p2.Age));
    

      

posted @ 2024-05-03 01:03  yinghualeihenmei  阅读(111)  评论(0编辑  收藏  举报