如何从linq-to-sql模型中获取随机集合?

时间:2010-01-17 05:14:07

标签: c# linq linq-to-sql random

这个的正确语法是什么?

var words= from h in db.Words
                  orderby(a => Guid.NewGuid()).ToList()) //error
                  select h;

var words= from h in db.Words
                  orderby((a => Guid.NewGuid()).ToList()) //error
                  select h;

var words= from h in db.Words
                  orderby(Guid.NewGuid()) //no error but doesn't sort
                  select h;

1 个答案:

答案 0 :(得分:3)

假设您不介意不在LINQ查询中嵌入所有代码,可以试试这个:

Random rnd = new Random();
var randomWords = from h in db.Words
                     orderby rnd.Next()
                     select h;

虽然你需要Guid方法:

var words = from h in db.Words
            orderby Guid.NewGuid()
            select h;