Shuffle in a subquery in LINQ

I have three object frameworks, Quiz, Question and Option. Quiz has a collection of Question objects and a Question has a collection of Option objects. I would like to go back from DBContext

a randomized list of questions for the specified quiz, and each question should include a random sort order of related options.

So far I've managed to get a random list of questions successfully, but I'm having trouble randomizing the options for a question.

Note. I have several different shuffle extension methods I wrote, in this example I am using Guid ordering for simplicity.

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

      

How can I shuffle the parameters randomly?

+3


source to share


1 answer


I'm not sure if LINQ-to-SQL will support converting such a specific function. In your downloads, if I had database access, I would create a stored procedure as described here to fetch random rows at the database level, Although this is not an optimal solution either (see the accepted answer to this question )

You can use the following approach (assuming you have fewer MAXINT questions):

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;

      



those. just generate some random unique query line numbers and select the appropriate lines.

WARNING! The optimization required before use is a dirty code prototype.

0


source







All Articles