linq: order by random

C#LinqRandom

C# Problem Overview


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

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);

C# Solutions


Solution 1 - C#

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.

As commented it might be better to use an algorithm like Fisher-Yates Shuffle, here is an implementation: https://stackoverflow.com/a/375446/284240

Solution 2 - C#

How big is the collection? Can you select them all into memory then choose a random collection? If so, then the Shuffle algorithm at https://stackoverflow.com/questions/1287567/c-is-using-random-and-orderby-a-good-shuffle-algorithm would be 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 an ordering by newid() ( https://stackoverflow.com/questions/52964/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.

Solution 3 - C#

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:

return (...-SQL-SELECT-LINQ-...)
    .ToList() //****
    .OrderBy(x => Guid.NewGuid()).Take(Limit).ToList();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser972087View Question on Stackoverflow
Solution 1 - C#Tim SchmelterView Answer on Stackoverflow
Solution 2 - C#tvanfossonView Answer on Stackoverflow
Solution 3 - C#Froschkoenig84View Answer on Stackoverflow