如何获得使用LINQ随机对象如何获得、对象、LINQ

2023-09-04 00:07:10 作者:你就是一条狗,谁骚跟谁走

我想获得在LINQ的一个随机的对象。这里是我做到了。

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 by the number of answers
int intRandomAnswer = r.Next(1, Answers.Count());
int count = 0;

//locate the answer
foreach(var Answer in Answers)
{
    if (count == intRandomAnswer)
    {
        SelectedPost = Answer;
        break;
    }
    count++;
}

这是做到这一点的最好方法是什么?

Is this the best way to do this?

推荐答案

什么:

SelectedPost = q.ElementAt(r.Next(1, Answers.Count()));

延伸阅读:的

下面的评论让密切相关的问题很好的贡献,我就包括他们在这里,自@Rouby指出,人们寻找的答案,这可能会觉得这个答案,它不会在这种情况下正确的

The comments below make good contributions to closely related questions, and I'll include them here, since as @Rouby points out, people searching for an answer to these may find this answer and it won't be correct in those cases.

随机元素在整个输入

为使所有元素的候选人中随机选择,您需要输入更改为 r.Next

To make all elements a candidate in the random selection, you need to change the input to r.Next:

SelectedPost = Answers.ElementAt(r.Next(0, Answers.Count()));

@Zidad增加了一个有用的扩展方法来获取随机元素在序列中的所有元素:

@Zidad adds a helpful extension method to get random element over all elements in the sequence:

public static T Random<T>(this IEnumerable<T> enumerable)
{
    if (enumerable == null)
    {
         throw new ArgumentNullException(nameof(enumerable));
    }

    // note: creating a Random instance each call may not be correct for you,
    // consider a thread-safe static instance
    var r = new Random();  
    var list = enumerable as IList<T> ?? enumerable.ToList(); 
    return list.Count == 0 ? default(T) : list[r.Next(0, list.Count)];
}