.Net4.0 之排序列表

今天第一次尝试了一个SortedSet的排序列表,该列表可以实现插入元素的自动排序(排序规则需要自己指定)

写了个小例子:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    public class Sort
    {
        public void Begin()
        {
            //新建排序对象,构造函数中指定排序的方法实例
            SortedSet<Person> sortset = new SortedSet<Person>(new PersonSort());
            sortset.Add(new Person { name = "wangjue", age = 11 });
            sortset.Add(new Person { name = "wangjue4", age = 44 });
            sortset.Add(new Person { name = "wangjue3", age = 33 });
            sortset.Add(new Person { name = "wangjue2", age = 22 });

            foreach (var item in sortset)
            {
                Console.WriteLine(string.Format("the name is {0}, age is:{1}", item.name, item.age));
                //the name is wangjue, age is:11
                //the name is wangjue2, age is:22
                //the name is wangjue3, age is:33
                //the name is wangjue4, age is:44
            }
        }
    }

    /// <summary>
    /// 比较类,需要实现IComparer接口中的Compare方法。
    /// </summary>
    public class PersonSort : IComparer<Person>
    {
        public int Compare(Person x, Person y)
        {
            if (x.age > y.age)// x>y返回正数
            {
                return 1;
            }
            else
                if (x.age < y.age)
                {
                    return -1;
                }
                else
                {
                    return 0;
                }
        }
    }

    public class Person
    {
        public string name;
        public int age;
    }
}


你可能感兴趣的:(.Net4.0 之排序列表)