I am trying the following codes to suffle the elements of an ArrayList– questionsAndSeperators. I am doing this with two ways.
Method 1:-
List<Question> questionList = this.questionsAndSeperators.Cast<Question>().ToList();
Random rng = new Random();
int questionCount = questionList.Count;
while (questionCount > 1)
{
questionCount--;
int index = rng.Next(questionCount + 1);
Question value = questionList[index];
questionList[index] = questionList[questionCount];
questionList[questionCount] = value;
}
Method 2:-
ArrayList questionList = this.questionsAndSeperators;
Random rng = new Random();
int questionCount = questionList.Count;
while (questionCount > 1)
{
questionCount--;
int index = rng.Next(questionCount + 1);
object value = questionList[index];
questionList[index] = questionList[questionCount];
questionList[questionCount] = value;
}
Here Question is a class.
Method 2 is working fine and suffling the elements of questionsAndSeperators, but Method 1 is not able to suffle the elements of questionsAndSeperators. What is the problem with Method 1??
Am I doing something wrong in method 1?
In Method 1 you create a
new List<Question>with all elements ofthis.questionsAndSeperators.Then you shuffle all elements of the
new List<Question>. But you don’t shuffle the elements ofthis.questionsAndSeperatorsbecause its another array.In Method 2 you access the
ArrayListdirectly and you shuffle the elements of theArrayList.