Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting 3 random records from a table

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

like image 215
Sniffer Avatar asked Jul 15 '12 19:07

Sniffer


2 Answers

var threeRandomFoos = foos.OrderBy(x => Guid.NewGuid()).Take(3);
like image 189
Darin Dimitrov Avatar answered Sep 16 '22 14:09

Darin Dimitrov


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?

like image 28
Akash Kava Avatar answered Sep 18 '22 14:09

Akash Kava