C#中List<T>中对T的Sort()

class Program
{
  static void Main(string[] args)
  {
    Random r = new Random();
    List<A> list_A = new List<A>();
    for (int i = 0; i < 10; i++)     {       A a = new A();       a.age = r.Next(1, 10);       list_A.Add(a);     }
    ConsolOut(list_A, "未排序:");
    list_A.Sort(new A());     ConsolOut(list_A, "排序以后:");   }      
  //输出函数   public static void ConsolOut(List<A> list, string s)   {     Console.Write(s);     for (int i = 0; i < list.Count; i++)     {       Console.Write(list[i].age + " ");     }     Console.WriteLine();   } }
//List中的类 public class A : IComparer<A>
{   public int age = 0;   public int Compare(A x, A y)   {     if (x.age > y.age)     {       return -1;//大的放左边     }     else if (x.age < y.age)     {       return 1;//小的放右边     }     else     {       return 0;//不变     }   } }

 

结果:

 

 

其实还有一种方法,也是需要实现接口的,都差不多。

posted on 2019-06-28 14:23  炼金师  阅读(4027)  评论(0编辑  收藏  举报

导航