list集合中进行排序

namespace list集合中的排序方法
{
    class Program
    {
        static void Main(string[] args)
        {
          //  List<int> list = new List<int>() { 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, };

            List<Person> list = new List<Person>() {
            new Person(){Name="wanjgia",Age=19,Email="[email protected]"},
            new Person(){Name="fgd",Age=30,Email="hk/[email protected]"},
            new Person(){Name="sdfa",Age=25,Email="[email protected]"},
            new Person(){Name="sdagda",Age=50,Email="[email protected]"},
           
            };
            list.Sort(new SortByAgeDesc());
            for (int i = 0; i < list.Count; i++)
            {
                Person pp = list[i] as Person;

                Console.WriteLine(pp.Name);
            }
            Console.ReadKey();
        }

        class SortByAgeDesc :IComparer<Person>
        {
            #region IComparable<Person>

            public int Compare(Person x, Person y)
            {
                return y.Age - x.Age;
            }

            #endregion
        
        }

        /// <summary>
        /// Person  实现  IComparable 接口之后可以排序
        /// </summary>
        class Person:IComparable<Person>
        {
            public string  Name { get; set; }
            public int Age { get; set; }
            public string  Email{ get; set; }


            public int CompareTo(Person other)
            {
                return this.Age - other.Age;
            }
        }
    }
}

猜你喜欢

转载自275055162.iteye.com/blog/2214747