0

I need shuffle to find a random content in the database but it will have a big impact if I find out about where to issues that are in the database.

I have look her: https://stackoverflow.com/a/654910/7180653

This is how I've tried to do it as I have described. But it gives error in my value in return.

Random rnd = new Random();
            int value = rnd.Next(db.Quiz.ToList().Count());
            List <QuizModelView> result = db.Quiz.Select(x => new QuizModelView
            {
                Heading = x.Heading,
                ReplayText = x.Reply.Text,
                ReplayCheck = x.Reply.CheckReply
            }).ToList();
            return result.Shuffle(value);
Community
  • 1
  • 1
Jesper P
  • 7
  • 3

1 Answers1

1

Seeing as you're happy to do it in memory rather than in the database itself (your ToList() is bringing it into memory) then you can use something like the Shuffle from this answer:

Shuffle any (I)List with an extension method based on the Fisher-Yates shuffle:

private static Random rng = new Random();  

public static void Shuffle<T>(this IList<T> list)  
{  
    int n = list.Count;  
    while (n > 1) {  
        n--;  
        int k = rng.Next(n + 1);  
        T value = list[k];  
        list[k] = list[n];  
        list[n] = value;  
    }  
}

Usage:

List <QuizModelView> result = db.Quiz.Select(x => new QuizModelView
{
    Heading = x.Heading,
    ReplayText = x.Reply.Text,
    ReplayCheck = x.Reply.CheckReply
}).ToList();
result.Shuffle();
return result;
Community
  • 1
  • 1
Tim
  • 5,443
  • 2
  • 22
  • 26