3

私は次のクラスを持っています:

public class Question
{
    public int    QuestionId { get; set; }
    public string Title { get; set; }
}

そして私が持っている変数で:

IEnumerable<Question> _questions = GetQuestions.Get();

変数 _questions にある質問のコレクションを取得し、コレクションから 1 ~ 4 個のランダムな質問のリストをランダムに返すにはどうすればよいですか?

4

2 に答える 2

2

Reservoir Samplingを使用して、未知のサイズのシーケンスを 1 回通過させて、N 個の項目のランダムなセットを選択できます。

public static List<T> RandomlyChooseItems<T>(IEnumerable<T> items, int n, Random rng)
{
    var result = new List<T>(n);
    int index = 0;

    foreach (var item in items)
    {
        if (index < n)
        {
            result.Add(item);
        }
        else
        {
            int r = rng.Next(0, index + 1);

            if (r < n)
                result[r] = item;
        }

        ++index;
    }

    return result;
}

次のように使用します。

IEnumerable<Question> questions = ...;
Random rng = new Random();
int questionCount = rng.Next(1, 5); // Get between 1 and 4 questions.

List<Question> randomQuestions = RandomlyChooseItems(questions, questionCount, rng);

これは通常、項目を配列にコピーしてFisher-Yates shuffle.アイテムの元のリストではなく、選択したアイテムを保存します。

于 2013-06-22T09:00:08.203 に答える