How to get a Random Object using Linq

前端 未结 9 1485
心在旅途
心在旅途 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: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(this IEnumerable enumerable)
            {
                var r = new Random();
                var list = enumerable as IList ?? enumerable.ToList();
                return list.ElementAt(r.Next(0, list.Count()));
            }
        }
    

提交回复
热议问题