linq: order by random

前端 未结 3 1284
执念已碎
执念已碎 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:15

    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.

    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.

提交回复
热议问题