Getting 3 random records from a table

試著忘記壹切 提交于 2020-01-13 09:13:51

问题


I've read multiple answers to a similar query, but none seem to hit the spot.

Imagine I have a table that contains 10 rows, how do I retrieve 3 random rows from this table using Entity Framework? Not just 1 random row, but 3 random rows - each being different from the other?

Thanks in advance


回答1:


var threeRandomFoos = foos.OrderBy(x => Guid.NewGuid()).Take(3);



回答2:


Instead, there is a simpler way,

var threeRandomFoos = foos.OrderBy( x=> SqlFunctions.Rand()).Take(3);

Guid.NewGuid will be little slower in performance, why not use Random specified by SqlFunctions itself?



来源:https://stackoverflow.com/questions/11494792/getting-3-random-records-from-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!