泛型IComparer排序

    class Program

    {

        static void Main(string[] args)

        {

            GetListTest();

        }



        private static void GetListTest()

        {

            DBHelper dbHelper = DBHelper.GetInstance();

            DataSet ds = dbHelper.GetSqlDataSet("SELECT name,age FROM tbl_test",null);

            

            List<Person> listPerson = new List<Person>();

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)

            {

                Person model = new Person();

                model.Name = ds.Tables[0].Rows[i]["name"].ToString();

                model.Age = ds.Tables[0].Rows[i]["age"].ToString();

                listPerson.Add(model);

            }



            //年龄排序

            Console.WriteLine("----年龄排序----");

            listPerson.Sort(new SortAge());

            for (int i = 0; i < listPerson.Count; i++)

            {

                Console.WriteLine(listPerson[i].Name + ":" + listPerson[i].Age);

            }

            Console.WriteLine("");

            //姓名排序

            Console.WriteLine("----姓名排序----");

            listPerson.Sort(new SortName());

            for (int i = 0; i < listPerson.Count; i++)

            {

                Console.WriteLine(listPerson[i].Name + ":" + listPerson[i].Age);

            }

        }



    }



    /// <summary>

    /// 排序实体

    /// </summary>

    class Person

    {

        private string name;

        /// <summary>

        /// 姓名

        /// </summary>

        public string Name

        {

            get { return name; }

            set { name = value; }

        }



        private string age;

        /// <summary>

        /// 年龄

        /// </summary>

        public string Age

        {

            get { return age; }

            set { age = value; }

        }

    }



    /// <summary>

    /// 年龄排序

    /// </summary>

    class SortAge :IComparer<Person>

    {

        public int Compare(Person x, Person y)

        {

            return x.Age.CompareTo(y.Age);

        }

    }



    /// <summary>

    /// 姓名排序

    /// </summary>

    class SortName : IComparer<Person>

    {

        public int Compare(Person x, Person y)

        {

            return x.Name.CompareTo(y.Name);

        }

    }

 

你可能感兴趣的:(compare)