Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select N Random Records with Linq

Tags:

linq-to-sql

I have a static table with 20+ records, I would like to select N (N<20) from that table in random manner. What is the best way to do it in the code with LINQ?

like image 256
dexter Avatar asked Dec 17 '10 19:12

dexter


2 Answers

Here's the best way:

var randomUsers = users.OrderBy(x => Guid.NewGuid()).Take(15);
like image 60
reach4thelasers Avatar answered Oct 13 '22 12:10

reach4thelasers


Maybe something like this would work:

int randomSkip;
int randomTake;

randomSkip = GenerateSomeAppropriateRandomNumber();
randomTake = GenerateSomeAppropriateRandomNumber();

resultSet = iEnumerable.Skip(randomSkip).Take(randomTake);
like image 35
Randy Minder Avatar answered Oct 13 '22 12:10

Randy Minder