How to get a Random Object using Linq

前端 未结 9 1510
心在旅途
心在旅途 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

    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?

提交回复
热议问题