星期六, 5月 09, 2015

[C#] IComparer<T>

閱讀 泛型介面 文章時,發現 IComparer<T> 範例,把之前這篇學習紀錄 [C#] IComparable 和 IComparer,改成利用泛型來練習

[C#] IComparer - 1



ClassDemo Project
using System.Collections;
namespace ClassDemo
{
    public class Car
    {
        public string Maker { get; set; }
        public int Year { get; set; }
        public decimal Price { get; set; }

        class SortByYear : IComparer<Car>
        {
            public int Compare(Car x, Car y)
            {
                return x.Year.CompareTo(y.Year);
            }
        }

        class SortByYearDesc : IComparer<Car>
        {
            public int Compare(Car x, Car y)
            {
                return y.Year.CompareTo(x.Year);
            }
        }

        private static IComparer<Car>[] Sorters = new IComparer<Car>[]
        {
            new SortByYear(),
            new SortByYearDesc()
        };

        public static IComparer<Car> 依年份排序
        {
            get { return Sorters[0]; }
        }

        public static IComparer<car> 依年份遞減排序
        {
            get { return Sorters[1]; }
        }

        public override string ToString()
        {
            return string.Format("{0} - {1} - {2}", this.Maker, this.Year, this.Price);
        }
    }
}

Show Project
using ClassDemo;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<Car> CarList = new List<Car>()
        {
            new Car() {Maker = "Ford", Year = 1992, Price = 2500},
            new Car() {Maker = "Buick",Year = 1932,Price = 2400},
            new Car() {Maker = "Ford", Year = 1932, Price = 1300},
            new Car() {Maker = "Dodge",Year = 1999,Price = 1000},
            new Car() {Maker = "Honda",Year = 1977,Price = 5600},
            new Car() {Maker = "Fiat",Year = 1988,Price = 1500}
        };
  
        CarList.Sort(Car.依年份遞減排序);

        foreach (Car item in CarList)
        {
            Response.Write(item.ToString() + "");
        }
    }
}

顯示結果
[C#] IComparer - 2

沒有留言:

張貼留言