linq: order by random

前端 未结 3 1291
执念已碎
执念已碎 2020-12-02 19:36

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_         


        
3条回答
  •  余生分开走
    2020-12-02 20:27

    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

提交回复
热议问题