C#3.0入門系列(六)-之OrderBy操作

來源:互聯網
上載者:User
本節講orderby操作.我突然在想這麼一個問題,讀者會T-SQL嗎?要是不知道,那我寫的是不是太簡單了呢?做個調查哦,不知道的舉手.
OrderBy操作
簡單的,按僱用日期排序,預設為升序

            var q =
                from e in db.Employees
                orderby e.HireDate
                select e;

帶where條件的,shipcity為london的。            var q =
                from o in db.Orders
                where o.ShipCity == "London"
                orderby o.Freight
                select o;

            var q =
                from o in db.Orders
                orderby o.Freight
                where o.ShipCity == "London"
                select o;

在這裡where和orderby的順序並不重要。而在T-SQL中,where和orderby有嚴格的位置限制。
OrderByDescending的,按價格降序。            var q =
                from p in db.Products
                orderby p.UnitPrice descending
                select p;

ThenBy的和ThenByDescending,也就是按多個列進行排序,第一個列子是先按city,city相同的再按contactname排序,第二個例子中,第二序列為降序。ThenBy:
            var q =
                from c in db.Customers
                orderby c.City, c.ContactName
                select c;

ThenByDescending:
            var q =
                from o in db.Orders
                where o.EmployeeID == 1
                orderby o.ShipCountry, o.Freight descending
                select o;

對這兩個句子解釋下。對於ThenBy操作,其級連形式為:
       var q = db.Customers.OrderBy(c => c.City).ThenBy(c => c.ContactName).ToList();
因為T-SQL中,並沒有ThenBy語句,其依然翻譯為OrderBy
所以,也可以用下面語句來表達
var q = db.Customers.OrderBy(c => c.ContactName).OrderBy(c => c.City).ToList();
所要注意的是,是兩個orderby的順序,多個orderby操作時,級連方式是按逆序.即先按city排時,city要放在最後。

對於降序的,用相應的降序操作符替換即刻。        var q = db.Customers.OrderByDescending(c => c.City).ThenByDescending(c => c.ContactName).ToList();

需要說明的是,orderby操作,不支援按type排序,也不支援匿名類。
比如  var q = db.Customers.OrderBy(c => c).ToList();和
var q = db.Customers.OrderBy(c => new {c.City,c.ContactName}).ToList();

會被拋出異常。但是,既然提了,大家在這個問題就不會犯錯誤,常見的錯誤是前面的操作有匿名類,再跟orderby時,比較的是類別。比如

var q = db.Customers.Select(c => new { c.City, c.Address }).OrderBy(c => c).ToList();

如果你想使用OrderBy(c => c),其前提條件是,前面步驟中,所產生的對象的類別必須為C#語言的基本類型。比如
var q = db.Customers.Select(c=>c.City).OrderBy(c => c).ToList();
city為string類型。

還有一點需要說明的時,linq和dlinq在orderby操作中,稍微有一點區別。linq支援按type排序,但是,需要你自己去實現IComparable介面。

比如語句:var q = db.Customers.ToList().OrderBy(c => c).ToList();
第一個ToList()會把資料庫中所有資料取出,放到記憶體中,以後所有的操作全部是對記憶體操作。後面的所有操作均為linq操作,不是dlinq。(這一點,我前面的文章中講過)如果,你想用按客戶進行排序,你必須在Customer類中,實現IComparable介面

其Customer類,必須從IComparable繼承,代碼如下,
  public partial class Customers : System.Data.Linq.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged,IComparable
Icomparable介面的具體實現如下:        #region IComparable Members

        public int CompareTo(object obj)
        {
            return this._CustomerID.CompareTo(((Customers)obj).CustomerID);
            //throw new Exception("The method or operation is not implemented.");
        }

        #endregion

Orderby操作,會自動調用該介面的方法,實現按類別排序。如果,你的對應檔中沒有實現該介面,系統會拋出異常。
你也可以使用generic,如下,
    public partial class Customers : System.Data.Linq.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged,IComparable<Customers>

        #region IComparable<Customers> Members

        public int CompareTo(Customers other)
        {
            return this.CustomerID.CompareTo(other.CustomerID);
            //throw new Exception("The method or operation is not implemented.");
        }

        #endregion

好處就是你無須把object強制轉化為customer類。
我們再來定義個,先按訂單號排序,相同訂單按產品號排序的。
    public partial class OrderDetails : System.Data.Linq.INotifyPropertyChanging, System.ComponentModel.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;
            //throw new Exception("The method or operation is not implemented.");
        }

好了,更多的功能,等待大家自己去實現。下次講Groupby操作。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.