Jainendra
Jainendra

Reputation: 25143

Struggling with the usage of List and ArrayList

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?

Upvotes: 2

Views: 180

Answers (2)

Martin Moser
Martin Moser

Reputation: 6269

In version one you are assign to a variable called "list", but then you are doing the shuffling in a variable called "questionList". I'm wondering that this compiles.

Upvotes: 0

lhlmgr
lhlmgr

Reputation: 2187

In Method 1 you create a new List<Question> with all elements of this.questionsAndSeperators. Then you shuffle all elements of the new List<Question>. But you don't shuffle the elements of this.questionsAndSeperators because its another array.

In Method 2 you access the ArrayList directly and you shuffle the elements of the ArrayList.

Upvotes: 3

Related Questions