C#中List中对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;//不变     }   } }

 

结果:

 

 

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM