首页 > 代码库 > 对象数组如何排序?

对象数组如何排序?

class Program    {       class Data : IComparable       {        public string name;  //这些必需要加public,否则会出错的        public int age;        public void input()        {            Console.WriteLine("输入姓名");            name = Console.ReadLine();            Console.WriteLine("输入年龄");            age = Convert.ToInt32(Console.ReadLine());        }        public int CompareTo(object obj)        { Data mc = (Data)obj;         if (this.age < mc.age) return -1;         if (this.age>mc.age) return 1;         return 0;        }      }         static void Main(string[] args)    {            int i = 0;            Data[] data = new Data[3];            for (i = 0; i < 3; i++)                data[i] = new Data();            for (i = 0; i < 3; i++)                data[i].input();            Array.Sort(data);            for (i = 0; i < 3; i++)            {                Console.Write("姓名:" + data[i].name);                Console.WriteLine("年龄:" + data[i].age);            }                       Console.ReadLine();      }    }

 

对象数组如何排序?