OrderBy 在 LINQ to SQL 中只能針對基本型別欄位排序;若嘗試對完整實體型別排序(如 OrderBy(c => c)),必須先將資料載入記憶體(ToList()),轉為 LINQ to Objects 執行,並由實體類別實作 IComparable 介面。
修改自動生成的 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) 即可直接使用。