除了使用集合元素默认的比较器进行排序,还可以传递实现IComparer接口的类,按自定义的排序逻辑进行排序。

下面用一个IT书籍,希望将书按价格从高向底排序

 public class Book
    {
    //定义书名属性
        private string _bookname;
        public string Bookname
        {
            get { return _bookname; }
            set { _bookname = value; }

        }
        //定义书籍分类属性
        private string _bookcategory;
        public string Bookcategory
        {
            get { return _bookcategory; }
            set { _bookcategory = value; }
        }
        //定义价格属性
        public double _price;
        public double Price
        {
            get { return _price; }
            set { _price = value; }
        }
        //定义书籍类的构造函数
        public Book( string bookname ,string bookcategory,double price)       
        {
            _bookname = bookname;
            _bookcategory = bookcategory;
            _price = price;
        }
        ///<summary>
        ///价格从高到死排序
        ///</summary>
        public class InstanceCompare : IComparer
        {
            public int Compare(object x, object y)
            {
            //使用书籍的价格进行比较
                double i = ((Book)y).Price - ((Book)x).Price;
                if (i > 0)
                {
                    return 1;
                }
                else if (i<0)
                {
                    return -1;
                }
                else
                {
                    return 0;
                }
            }
        }
    }
   ///按照书名从高到底排序

    public class BookNameCompare :IComparer
    {
        public int Compare(object x, object y)
        {
        //调用.net预定义的按指定忽略大小写比较器比较书名
            return new CaseInsensitiveComparer().Compare((((Book)y).Bookname), ((Book)x).Bookname);
        }
    }

   // #region 复杂排序
                Book[] books = new Book[8] { new Book("C#书籍z", "C#", 45.5), new Book("C#书籍f", "C#", 55.8), new Book("Delohi书籍1", "Delohi", 78), new Book("C#书籍x", "C#", 55.9), new Book("ASP.NET", "ASP.NET", 66), new Book("Delohi书籍2", "Delohi", 79), new Book("C#书籍y", "C#", 60), new Book("C#书籍b", "C#",80) };
                ArrayList al = new ArrayList(books);
                Console.WriteLine("没有排序前的序列------------");
                DisplayResult(al);
                //对数组按价格进行排序调用InstanceCompare比较器
                al.Sort(new 基础笔记学习.Book.InstanceCompare());
                Console.WriteLine("排序以后的输出--------------");
                DisplayResult(al);
                Console.WriteLine("------------------------------------");
                //对数组进行按书名进行排列,调用BookNameCompare
                al.Sort(new 基础笔记学习.Book.InstanceCompare());
                DisplayResult(al);
                #endregion

static void DisplayResult(ArrayList ls)
        {
            foreach (Book   item in ls)
            {
                Console.WriteLine("书名:{0},价格:{1}",item.Bookname,item.Price);
            }
        }

Posted on 2010-12-29 20:09  lichen396116416  阅读(205)  评论(0编辑  收藏  举报