木子屋 Dnawo's BLOG

实现List<T>元素排序两种方法

👤 dnawo 📅 2012-09-28 👁 5000 👍 0 💬 0 🔄 来源:本站原创
1.调用Sort(Comparison<T> comparison)

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        /// <summary>
        /// 排序方法
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public static int FunCompare(Person x, Person y)
        {
            return x.Age.CompareTo(y.Age);
        }

        static void Main(string[] args)
        {

            List<Person> people = new List<Person>();
            people.Add(new Person() { Name = "person1", Age = 20 });
            people.Add(new Person() { Name = "person2", Age = 50 });
            people.Add(new Person() { Name = "person3", Age = 30 });

            //排序
            people.Sort(FunCompare); //或:people.Sort((x, y) => x.Age.CompareTo(y.Age));

            foreach (Person person in people)
                Console.WriteLine("{0},{1}", person.Name, person.Age);

            Console.ReadKey();
        }
    }
}

2.调用Sort(IComparer<T> comparer)

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    /// <summary>
    /// 排序类
    /// </summary>
    class ClsCompare : IComparer<Person>
    {
        public int Compare(Person x, Person y)
        {
            return x.Age.CompareTo(y.Age);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            List<Person> people = new List<Person>();
            people.Add(new Person() { Name = "person1", Age = 20 });
            people.Add(new Person() { Name = "person2", Age = 50 });
            people.Add(new Person() { Name = "person3", Age = 30 });

            //排序
            people.Sort(new ClsCompare());

            foreach (Person person in people)
                Console.WriteLine("{0},{1}", person.Name, person.Age);

            Console.ReadKey();
        }
    }
}

评论(0)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 SQL Server2008修改表提示启用了"阻止保存要求重新创… 下一篇 → TimeSpan小结