Linq: random order

How can I change the code below to get 50 different random data from the database each time?

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); 
+45
c # random linq
Feb 26 2018-12-12T00:
source share
3 answers

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 it's LINQ-to-SQL, you can simply add ORDER BY NEWID() to the SELECT statement.

As already noted, it might be better to use an algorithm like Fisher-Yates Shuffle , here is the implementation: https://stackoverflow.com/a/212718/

+82
Feb 26 2018-12-12T00:
source share

How big is the collection? Can you select them all in memory and then select a random collection? If so, then Shuffle's algorithm. Is using Random and OrderBy a good shuffle algorithm? - a good choice.

 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 newid() ordering 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 # in LINQ to SQL / Entities.

+9
Feb 26 2018-12-12T00:
source share

If you have 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 should be a LIST, so maybe you need to change the list before using the OrderBy-NewGuid method:

 return (...-SQL-SELECT-LINQ-...) .ToList() //**** .OrderBy(x => Guid.NewGuid()).Take(Limit).ToList(); 
+3
Jun 08 '15 at 8:13
source share



All Articles