Often you come across a requirement where you need to create a random list of numbers, objects etc. Or sometime you need to rearrange an exosting list in a random order. In the past you may have used some third party library or developed a custom implementation that accomplished the task.
In .Net8, Microsoft has introduced a new functionality that provides ability to shuffle a collection in a random order. Following code snippet shows the use of new Random.Shuffle method. I use this in an exam question application. It takes a list of questions and shuffles them in a random order.
var usedQuestionList = await query.ToListAsync(); var allQuestions = await _questionRepository.Table.Select(q=>q.Id).ToListAsync(); var unusedQuestions = allQuestions.Except(usedQuestionList).ToArray(); (new Random()).Shuffle(unusedQuestions); var questionIds = unusedQuestions.Take(numberOfQuestions); return questionIds.ToList();