【发布时间】:2013-03-30 21:08:53
【问题描述】:
如何使用 Linq 的查询语法返回随机记录?
类似于下面的 tsql 语句:
select top 10 * from sometable ORDER BY NewID()
【问题讨论】:
如何使用 Linq 的查询语法返回随机记录?
类似于下面的 tsql 语句:
select top 10 * from sometable ORDER BY NewID()
【问题讨论】:
这应该是等价的:
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.
【讨论】:
您可以将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);
【讨论】: