3

I have three entity framework objects, Quiz, Question, and Option. A Quiz has a collection of Question objects, and a Question has a collection of Option objects. I would like to return from the DBContext a randomized list of questions for a specified quiz and each question should include a randomly sorted collection of associated Options.

So far, I have been able to get the random list of questions out successfully, but I am having trouble randomizing the options for the question.

Note: I have a couple of different shuffling extension methods I have written, in this example I am using ordering by a Guid for sake of simplicity.

var questions = db.Questions.Where(q => q.QuizId == quizId).Include(q => q.Options).OrderBy(a => Guid.NewGuid());

How can I randomly shuffle the Options?

4

1 回答 1

0

我不确定 LINQ-to-SQL 是否支持转换这种特定功能。在您的引导中,如果我可以访问数据库,我将创建一个存储过程,如此处所述,以获取数据库级别的随机行。虽然,这也是一个非最佳解决方案(请参阅此问题的已接受答案)

您可以采用以下方法(假设您的问题少于 MAXINT):

Random random;
var c = Questions.Count();

var randomNumbers = new List<int>();
var fetchedQuestions = new List<Question>();
var randomNumber = random.Next(1,c);

for (int i = 0; i < maxQuestions; i++) {
    while (randomNumbers.Contains(randomNumber))
        randomNumber = random.Next(1,c);
    randomNumbers.Add(randomNumber);
    fetchedQuestions.Add(Questions.ElementAt(randomNumber));
}
return fetchedQuestions;

即只生成一些随机的唯一问题行号并获取相应的行。

警告!使用前需要优化 - 这是一个肮脏的代码原型。

于 2013-01-22T10:30:07.063 回答