问题
I've seen the following:
Random element of List<T> from LINQ SQL
What I'm doing now - to get three random elements - is the following:
var user1 = users.ElementAt( rand.Next( users.Count() ) );
var user2 = users.Where(u => !u.Equals(user1)).ElementAt( rand.Next( users.Count() ) );
var user3 = users.Where(u => !u.Equals(user1) && !u.Equals(user2)).ElementAt( rand.Next( users.Count() ) );
But this is obviously unweildy and inefficient. How can I do this elegantly and efficiently with one trip to the database?
EDIT: Based on below answer, I made the following extension method:
public static IQueryable<T> SelectRandom<T>(this IQueryable<T> list, int count) {
return list.OrderBy(_ => Guid.NewGuid()).Take(count);
}
var result = users.SelectRandom(3);
BUT it seems like this would be inefficient for large datasets. Another proposal is to take the .Count() of the IQueryable, select n random numbers that fall within that result, and then shoot a query to the db with the selected random indices... but the Count() might be expensive here.
回答1:
The following should work:
users.OrderBy(_ => Guid.NewGuid()).Take(3)
This retrieves the first 3 elements from the users table, while sorting them by a value which is different each time.
Compared to AD.Net's answer.. well you'd require a list of userids generated randomly.. it doesn't suggest a way to do that
来源:https://stackoverflow.com/questions/23840973/how-to-efficiently-retrieve-a-list-of-random-elements-from-an-iqueryable