Selecting a random record from Entity Framework database without OrderBy
I am trying to get a random entry from the database:
personToCall = db.Persons.Skip(toSkip).Take(1).First();
but I am getting an exception that tells me:
{"The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'."}
Can I do it without OrderBy
? Sorting a data structure (O (nlogn)) to select a random item (which should be constant) doesn't seem wise.
EDIT: I am using Entity Framework 6.1.1.
source to share
First you need to get a random number from 1 to the maximum record, see this
Random rand = new Random();
int toSkip = rand.Next(1, db.Persons.Count);
db.Persons.Skip(toSkip).Take(1).First();
with ordering you can use Guid.NewGuid ()
db.Persons.OrderBy(x=>x.Guid.NewGuid()).Skip(toSkip).Take(1).FirstOrDefault();
source to share
There is no way to do this without an ordering clause.
personToCall = db.Persons.OrderBy (r => Random.Next ()). First ();
This can be slow depending on the size of your faces table, so if you want to do it quickly, you need to add a column to Person, or join it to the Person random numbers and keys dictionary, then order. But this is rarely a smart decision.
Better to ask a higher level question about the overall task.
source to share
To avoid OrderBy, dump to the list and randomize against the index:
V. B.
With New List(Of Persons)
.AddRange(db.Persons)
PersonToCall = .Item(New Random().Next(0, .Count - 1))
End With
FROM#
var people = new List<Persons>();
people.AddRange(db.Persons);
personToCall = people.Item(new Random().Next(0, people.Count - 1));
source to share