C# linq:随机排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9449452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
linq: order by random
提问by user972087
How can I change below code, to each time get 50 different random data from database?
如何更改以下代码,每次从数据库中获取 50 个不同的随机数据?
return (from examQ in idb.Exam_Question_Int_Tbl
where examQ.Exam_Tbl_ID==exam_id
select examQ).OrderBy(x=>x.Exam_Tbl_ID).Take(50);
采纳答案by Tim Schmelter
http://msdn.microsoft.com/en-us/library/system.guid.newguid.aspx
http://msdn.microsoft.com/en-us/library/system.guid.newguid.aspx
return (from examQ in idb.Exam_Question_Int_Tbl
where examQ.Exam_Tbl_ID==exam_id
select examQ).OrderBy(x => Guid.NewGuid()).Take(50);
If this is LINQ-to-SQL you could simply add a ORDER BY NEWID()to your SELECT statement.
如果这是 LINQ-to-SQL,您可以简单地将 a 添加ORDER BY NEWID()到您的 SELECT 语句。
As commented it might be better to use an algorithm like Fisher-Yates Shuffle, here is an implementation: https://stackoverflow.com/a/375446/284240
正如评论的那样,使用像Fisher-Yates Shuffle这样的算法可能会更好,这是一个实现:https: //stackoverflow.com/a/375446/284240
回答by tvanfosson
How big is the collection? Can you select them all into memory then choose a random collection? If so, then the Shuffle algorithm at Is using Random and OrderBy a good shuffle algorithm?would be a good choice.
收藏量有多大?您可以将它们全部选择到内存中然后选择一个随机集合吗?如果是这样,那么使用 Random 和 OrderBy的 Shuffle 算法是一个好的 shuffle 算法吗?会是一个不错的选择。
return idb.Exam_Question_Int_Tbl
.Where( e => e.Exam_Tbl_ID == exam_id )
.ToList()
.Shuffle()
.Take( 50 );
If not, then I would suggest a stored procedure that does an ordering by newid()( SQL Server Random Sort). I don't think there is any way to translate an expression based on a random number generator in C# to LINQ to SQL/Entities.
如果没有,那么我会建议一个按newid()(SQL Server Random Sort)排序的存储过程。我认为没有任何方法可以将基于 C# 中随机数生成器的表达式转换为 LINQ to SQL/Entities。
回答by Froschkoenig84
If you've the same problem, I had...
如果你有同样的问题,我有...
int Limit = 24;
return (from Q in Context.table
where Q.some_key == 1234
select new classDataType() {
FirstAttribute = Q.FirstCol,
SecondAttribute = Q.SecondCol,
ThirdAttribute = Q.ThirdCol
}).ToList().OrderBy(x => Guid.NewGuid()).Take(Limit).ToList();
After sql-linq it needs to be a LIST, so maybe U need changing to a list, before you're using the OrderBy-NewGuid-Method:
在 sql-linq 之后它需要是一个列表,所以在你使用 OrderBy-NewGuid-Method 之前,你可能需要更改为一个列表:
return (...-SQL-SELECT-LINQ-...)
.ToList() //****
.OrderBy(x => Guid.NewGuid()).Take(Limit).ToList();

