How to efficiently retrieve a list of random elements from an IQueryable?

一个人想着一个人 提交于 2020-05-15 11:39:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!