zoukankan      html  css  js  c++  java
  • C# 自定义排序

    /// <summary>
    /// 实体
    /// </summary>
    public class Product
    {
    public int ID { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public DateTime PublishDate { get; set; }
    }
    /// <summary>
    /// 实体集合
    /// </summary>
    public class PrductList
    {
    public List<Product> Books { get; set; }
    }

    //一个排序依据枚举:
    public enum ComparisonType
    {
    Price, PublishDate
    }

    //一个排序基类,实现具体排序
    public class BookComparison : IComparer<Product>
    {
    private ComparisonType type;

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

    public int Compare(Product x, Product y)
    {
    int order = 0;
    switch (this.type)
    {
    case ComparisonType.Price:
    order = y.Price.CompareTo(x.Price);//更换x和y的顺序可以实现升序或者降序功能
    break;
    case ComparisonType.PublishDate:
    order = y.PublishDate.CompareTo(x.PublishDate);//更换x和y的顺序可以实现升序或者降序功能
    break;
    default:
    break;
    }
    int d = order;
    return order;
    }
    }
    public class MyTest
    {
    public void test()
    {
    PrductList list = new PrductList();
    List<Product> Books = new List<Product>();
    list.Books = Books;
    list.Books.Add(new Product()
    {
    ID = 1,
    Name = "LiSi",
    Price = 12.5M,
    PublishDate = DateTime.Parse("2016-06-03")
    });
    list.Books.Add(new Product()
    {
    ID = 1,
    Name = "Zhangsan",
    Price = 12.8M,
    PublishDate = DateTime.Parse("2016-06-05")
    });
    list.Books.Add(new Product()
    {
    ID = 1,
    Name = "Wangwu",
    Price = 11.5M,
    PublishDate = DateTime.Parse("2016-06-01")
    });
    list.Books.Sort(new BookComparison(ComparisonType.Price).Compare);
    foreach (var item in list.Books)
    {
    Console.WriteLine(string.Format("{0}:{1}, {2}", item.Name, item.Price, item.PublishDate.ToString()));
    }
    }
    }

  • 相关阅读:
    Django入门
    外星人入侵完整版
    外星人入侵
    简单的socket通信
    购物车程序
    列表的使用&元组
    三目运算的使用&bytes类型转str类型
    hdu 2586 How far away ?
    hdu 1075 What Are You Talking About
    洛谷 P2292 [HNOI2004]L语言
  • 原文地址:https://www.cnblogs.com/niuzaihenmang/p/5620595.html
Copyright © 2011-2022 走看看