首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 3.0 入門系列(六):OrderBy 排序進階——實作 IComparable 實現型別級排序

     編輯:關於C語言

LINQ to Objects vs LINQ to SQL 的排序差異

OrderBy 在 LINQ to SQL 中只能針對基本型別欄位排序;若嘗試對完整實體型別排序(如 OrderBy(c => c)),必須先將資料載入記憶體(ToList()),轉為 LINQ to Objects 執行,並由實體類別實作 IComparable 介面。

實作 IComparable<T> 實現客戶排序

修改自動生成的 partial 類別(建議另建 partial 檔案):

public partial class Customers : INotifyPropertyChanging, INotifyPropertyChanged, IComparable<Customers>
{
    #region IComparable<Customers> Members
    public int CompareTo(Customers other)
    {
        return this.CustomerID.CompareTo(other.CustomerID);
    }
    #endregion
}

使用泛型版本 IComparable<T> 可避免 object 裝箱與轉型開銷。

多欄位複合排序:訂單明細範例

public partial class OrderDetails : INotifyPropertyChanging, INotifyPropertyChanged, IComparable<OrderDetails>
{
    #region IComparable<OrderDetails> Members
    public int CompareTo(OrderDetails other)
    {
        int k = this.OrderID - other.OrderID;
        if (k == 0)
            k = this.ProductID - other.ProductID;
        return k;
    }
    #endregion
}

先依 OrderID 排序,相同則依 ProductID 排序。實作介面後,OrderBy(o => o) 即可直接使用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved