How to get a Random Object using Linq

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

    var rand = new Random();
    var selectedPost = q.Skip(rand.Next(0, q.Count())).Take(1).FirstOrDefault();
    

    Optimally, you want to only ever make the function query for a single value, so you set up the Skip/Take to jump up to the sequence number matching the random number you're generating (bounded by dataset's itemcount, so the missing row problem bounding based on MAX(pkey) isn't an issue) and then snag the first item at that point in the sequence.

    In SQL this is the same as querying for SELECT Count(*) FROM q, then SELECT * FROM q LIMIT {0}, 1 where {0} is rand.Next(0, count), which should be pretty efficient.

提交回复
热议问题