轉:使用linq to sql 隨機取一行資料的方法

來源:互聯網
上載者:User

標籤:

原文地址:http://outofmemory.cn/code-snippet/1760/usage-linq-to-sql-suiji-take-yixing-data-method 雖然這看來已經不是真正的原文地址了

在linq to sql中我們可以通過建立一個假的使用者自訂函數的方法來實現隨機取一行資料的方法。

首先要在DataContext的類中添加使用者自訂函數,最好是放在partial class中:

partial class MyDataContext {     [Function(Name="NEWID", IsComposable=true)]      public Guid Random()      { // to prove not used by our C# code...          throw new NotImplementedException();      }}

現在我們可以使用 order by ctx.Random() 這樣的效果是在sql-server中執行order by NEWID()

例如:

var cust = (from row in ctx.Customers           where row.IsActive // your filter           orderby ctx.Random()           select row).FirstOrDefault();

注意: 這個方法如果用在資料量很大的表中有可能會有效能問題。

轉:使用linq to sql 隨機取一行資料的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.