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.