How to get a Random Object using Linq

前端 未结 9 1442
心在旅途
心在旅途 2020-12-29 02:34

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         


        
相关标签:
9条回答
  • 2020-12-29 03:32

    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.

    0 讨论(0)
  • 2020-12-29 03:32

    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?

    0 讨论(0)
  • 2020-12-29 03:33

    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()));
            }
        }
    
    0 讨论(0)
提交回复
热议问题