0
如何使用Linq的查詢語法來返回隨機記錄?如何使用Linq的查詢語法來返回隨機記錄?
類似下面的TSQL語句:
select top 10 * from sometable ORDER BY NewID()
如何使用Linq的查詢語法來返回隨機記錄?如何使用Linq的查詢語法來返回隨機記錄?
類似下面的TSQL語句:
select top 10 * from sometable ORDER BY NewID()
您可以使用Guid.NewGuid()
與LINQ
var results = db.sometable.OrderBy(r => Guid.NewGuid()).Take(10);
或查詢語法:
var results = (from s in sometable orderby Guid.NewGuid() select s).Take(10);
這應該是等價的:
var query =
(from s in sometable
orderby Guid.NewGuid() //Ordering by Guid.NewGuid() is the same as newid()
select s)
.Take(10); //This cannot be done in query syntax.