Hi guys,
how I can get a random row from a selection in my linq query?
I tried:
Bot bot = (from a in dc.Bot
select a).OrderBy(x => Guid.NewGuid()).First();
But doesn't work, I ever get the same.
Hi guys,
how I can get a random row from a selection in my linq query?
I tried:
Bot bot = (from a in dc.Bot
select a).OrderBy(x => Guid.NewGuid()).First();
But doesn't work, I ever get the same.
I would use Skip
var query = from a in dc.Bot
select a;
int random = new Random().Next(query.Count);
Bot bot = query.Skip(random).First();
Something like this might work:
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()
I have an extension method for that 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;
}
}
Usage:
Random rnd = new Random();
Bot bot = (from a in dc.Bot select a).PickRandomOne(rnd);
The advantage of this method is that you don't need to know how many items there are beforehand, so you don't have to run the query twice.