比较来自两个不同列表的元素时遇到问题

Having problems comparing elements from two different lists

我目前正在尝试创建打字测试程序。我在比较这两个列表 list1(10 个随机词)和 list2(10 个用户输入)中的元素时遇到问题。这是我收到的错误消息:ArgumentOutOfRangeException was unhandled

我不确定为什么,但是当我进入调试菜单时,它将 list1 的值显示为 Count = 1,然后 list2 的值显示为 Count = 10。两个列表中的所有元素都是字符串。所以我的问题是如何按顺序比较这些列表中的元素(第一个列表的第一个元素与第二个列表的第一个元素)等等。

我对编码还比较陌生,我不明白为什么下面的代码不起作用。我已经尝试解决这个问题几个小时了,所以在此先感谢您的帮助!

`for (int i = 0; i < gameLength; i++) // The code below will loop 10 times
        {   
            List<string> list1 = new List<string>(); 
            string chosenWord = SelectWord(); // Selects a random word
            Console.Write(chosenWord + " "); // Prints the selected word
            list1.Add(chosenWord); // Adds the selected word to the list

            if (i == 9) // True once above code has been performed 10 times
            {   
                Console.WriteLine();
                List<string> list2 = new List<string>();

                for (int b = 0; b < 10; b++) // This will also loop 10 times
                {   
                    string userValue = UserInput(); // Gets user input
                    list2.Add(userValue); // Adds user value to list
                }

                for (int t = 0; t < 10; t++)
                {
                    if (list1[t] == list2[t]) // Here is the error
                    { 
                        score++;
                        Console.WriteLine(score);

                        /* The error occurs on the second pass
                         * when the value of t becomes 1, But i don't  
                        */ understand why that doesn't work.
                    }
                }
            }
        }`

尝试在第一个 for 循环之外声明 List<string> list1 = new List<string>();,我认为你的问题是因为你每次都声明 list1,所以最后 list1 的迭代计数只有1个,因为你每次做新的。

我认为这是问题所在。

根据你的立场,我会这样做:

List<string> list1 = new List<string>(); 
for (int i = 0; i < gameLength; i++) // The code below will loop 10 times
{   
    string chosenWord = SelectWord(); // Selects a random word
    Console.Write(chosenWord + " "); // Prints the selected word
    list1.Add(chosenWord); // Adds the selected word to the list
}

List<string> list2 = new List<string>();
for (int b = 0; b < 10; b++) // This will also loop 10 times
{   
    string userValue = UserInput(); // Gets user input
    list2.Add(userValue); // Adds user value to list
}

int score = 0;
for (int t = 0; t < 10; t++)
{
    if (list1[t] == list2[t]) // Now should work
    { 
        score++;        
    }
}

Console.WriteLine(score);