如何使用 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);