0

如何使用 Linq 的查询语法返回随机记录?

类似于以下 tsql 语句:

select top 10 * from sometable ORDER BY NewID()
4

2 回答 2

2

这应该是等效的:

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.
于 2013-03-30T21:11:29.750 回答
1

您可以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);
于 2013-03-30T21:11:21.703 回答