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?
Asked
Active
Viewed 2.0k times
19
-
possible duplicate of [Random row from Linq to Sql](http://stackoverflow.com/questions/648196/random-row-from-linq-to-sql) – Ahmad Mageed Dec 17 '10 at 19:30
-
@Ahmad, no it's not a duplicate as I was to be selecting a constant number (lets say 5) records but they have to be random. So I want to sort the dataset in the random manner before I do .take(5) – dexter Dec 17 '10 at 19:35
-
1the solution in my proposed duplicate would work. You would query the items, order by the random function, then `.Take(N)` at the end of it. Or am I misunderstanding? – Ahmad Mageed Dec 17 '10 at 19:52
2 Answers
109
Here's the best way:
var randomUsers = users.OrderBy(x => Guid.NewGuid()).Take(15);

reach4thelasers
- 26,181
- 22
- 92
- 123
-
2i know this was ages ago but your answer worked perfectly for me i was lookinf for ages!! thabks – anna Jan 28 '13 at 16:04
-
1Is generating a GUID for each element sensible? What's the complexity this vs that of just picking a random selection? – Dave Hillier Apr 20 '13 at 14:26
-
6Dave Hillier, I think the issue with just picking a "random selection" is having to solve the random element of it. There is a cost to generating the Guids and sorting on them, but it is otherwise a brilliantly clean and reliable bit of code for getting a random set back. (Being that the GUIDS will create a new random order every time the query is run.) If the recordset was large then it might make sense to create a bit of code that would randomly select N, unique records, at random, from the resultset. – Dylan - INNO Software Oct 11 '13 at 18:40
-
2
Maybe something like this would work:
int randomSkip;
int randomTake;
randomSkip = GenerateSomeAppropriateRandomNumber();
randomTake = GenerateSomeAppropriateRandomNumber();
resultSet = iEnumerable.Skip(randomSkip).Take(randomTake);

Randy Minder
- 47,200
- 49
- 204
- 358
-
4no, I always want to select a fixed amount of records. But the records within that subset should be random. – dexter Dec 17 '10 at 19:36
-
1With this solution, each item has not the same probability of being selected – Daniel Argüelles May 10 '16 at 13:38