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

时间:2022-12-15 20:44:24

This question already has an answer here:

这个问题在这里已有答案:

How can I use query syntax from Linq for return random records?

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

Something like the following tsql statement:

像下面的tsql语句:

select top 10 * from sometable ORDER BY NewID()

2 个解决方案

#1


2  

This should be equivalent:

这应该是等价的:

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.

#2


1  

You can use Guid.NewGuid() with linq

您可以将guid.NewGuid()与linq一起使用

var results = db.sometable.OrderBy(r => Guid.NewGuid()).Take(10);

or in query syntax:

或者在查询语法中:

var results = (from s in sometable orderby Guid.NewGuid() select s).Take(10);

#1


2  

This should be equivalent:

这应该是等价的:

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.

#2


1  

You can use Guid.NewGuid() with linq

您可以将guid.NewGuid()与linq一起使用

var results = db.sometable.OrderBy(r => Guid.NewGuid()).Take(10);

or in query syntax:

或者在查询语法中:

var results = (from s in sometable orderby Guid.NewGuid() select s).Take(10);