如何从linq查询中的选择中获取随机行?
我试过了:
Bot bot = (from a in dc.Bot
select a).OrderBy(x => Guid.NewGuid()).First();
但是不起作用,我也得到了同样的效果。
答案 0 :(得分:8)
我会使用Skip
var query = from a in dc.Bot
select a;
int random = new Random().Next(query.Count);
Bot bot = query.Skip(random).First();
答案 1 :(得分:4)
这样的事可能有用:
var random = new Random();
var allBots = (from a in dc.Bot select a);
var randomAmountToSkip = random.NextInt(allBots.Count());
var anyBot = allBots.Skip(randomAmountToSkip).First()
答案 2 :(得分:2)
我有in my archive的扩展方法:
static class IEnumerableExtensions {
public static T PickRandomOne<T>(this IEnumerable<T> list, Random rnd) {
T picked = default(T);
int cnt = 0;
foreach (T item in list) {
if (rnd.Next(++cnt) == 0) {
picked = item;
}
}
return picked;
}
}
用法:
Random rnd = new Random();
Bot bot = (from a in dc.Bot select a).PickRandomOne(rnd);
此方法的优点是您不需要事先知道有多少项,因此您不必运行两次查询。