I am trying to get a random object within linq. Here is how I did.
//get all the answers
var Answers = q.Skip(1).Take(int.MaxValue);
//get the random number
Late to the party but this is a high-up Google result. A succinct version could be:
var rnd = new Random();
var SelectedPost = q.OrderBy(x => rnd.Next()).Take(1);
It has the disadvantage that it'll apply a random number to all elements, but is compact and could easily be modified to take more than one random element.
I'm posting an answer because I don't have enough reputation to comment.
I like this answer:
SelectedPost = q.ElementAt(r.Next(1, Answers.Count()));
But ElementAt is zero based, surely starting at 1 and going to Answers.Count() you are going to end up potentially throwing an out of range, and you are never going to get the first entity.
Wouldn't
SelectedPost = q.ElementAt(r.Next(0, Answers.Count() - 1));
Be better?
Generic extension method based on the accepted answer (which doesn't always skip the first, and only enumerates the enumerable once):
public static class EnumerableExtensions
{
public static T Random<T>(this IEnumerable<T> enumerable)
{
var r = new Random();
var list = enumerable as IList<T> ?? enumerable.ToList();
return list.ElementAt(r.Next(0, list.Count()));
}
}