根据特殊实体业务,实现自定义排序

两个类对象:

  public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public DateTime PublishDate { get; set; }
    }
    public class PrductList
    {
        public List<Product> Books { get; set; }
    }

一个排序依据枚举:

 public enum ComparisonType
    {
        Price, PublishDate
    }

一个排序基类,实现具体排序

 // Author  : zzl
    public class BookComparison : IComparer<Product>
    {
        private ComparisonType type;

        public BookComparison(ComparisonType type)
        {
            this.type = type;
        }

        public int Compare(Product x, Product y)
        {
            switch (this.type)
            {
                case ComparisonType.Price:
                    return x.Price.CompareTo(y.Price);
                    break;
                case ComparisonType.PublishDate:
                    return x.PublishDate.CompareTo(y.PublishDate);
                    break;
                default:
                    break;
            }

            return 0;
        }
    }

排序并输出结果:

   bs.Books.Sort(new BookComparison(ComparisonType.Price).Compare);
            foreach (var item in bs.Books)
            {
                Console.WriteLine(string.Format("{0}:{1}, {2}", item.Name, item.Price, item.PublishDate.ToString()));
            }
   Console.ReadKey();

posted @ 2012-01-31 15:53  张占岭  阅读(485)  评论(0编辑  收藏  举报