供 List<T> 做多重條件排序的通用元件 4

  • 1093
  • 0

供 List<T> 做多重條件排序的通用元件 4

這篇直接使用 C# 3.0 開始提供的 Linq 。

Visual Studio 2005 之後的版本才支援此方式。

 

{
    var list = new List<Item>();
    list.Add(new Item("2013-10-1", "G", 6, 2100));
    list.Add(new Item("2013-10-3", "D", 6, 1300));
    list.Add(new Item("2013-10-3", "F", 5, 1100));
    list.Add(new Item("2013-10-3", "A", 6, 1100));
    list.Add(new Item("2013-10-5", "A", 7, 5100));
    list.Add(new Item("2013-10-6", "A", 9, 2100));
    list.Add(new Item("2013-10-7", "R", 6, 1100));

    Dump("[未排序]", list);

    Dump("[依 Date, Qty, Name 排序]",
        list
            .OrderBy(o => o.Date)
            .ThenBy(o => o.Qty)
            .ThenBy(o => o.Name));
    Dump("[依 Name, Price 排序]",
        list
            .OrderBy(o => o.Name)
            .ThenBy(o => o.Price));
    Dump("[依 Qty, Name 排序]",
        list
            .OrderBy(o => o.Qty)
            .ThenBy(o => o.Name));

    Console.ReadLine();
}

static void Dump(string caption, IEnumerable<Item> list)
{
    Console.WriteLine();
    Console.WriteLine(caption);
    foreach (var i in list)
        Console.WriteLine(i);
}

class Item
{
    public DateTime Date { get; set; }
    public string Name { get; set; }
    public int Qty { get; set; }
    public decimal Price { get; set; }
    public Item(string date, string name, int qty, decimal price)
        : this(DateTime.Parse(date), name, qty, price)
    { }
    public Item(DateTime date, string name, int qty, decimal price)
    {
        Date = date.Date;
        Name = name;
        Qty = qty;
        Price = price;
    }
    public override string ToString()
    {
        return string.Format(
            "Date: {0:yyyy-MM-dd}, Name: {1}, Qty: {2}, Price: {3}",
            Date, Name, Qty, Price);
    }
}