Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
60 views
in Technique[技术] by (71.8m points)

c# - Why do I get an error in the loop in this code?

I can do this with "for" loop, but why does it say it's outside of bounds of the array when I try with "for each"? The text file numbers are 9 2 1 3 4 4.

 string text = File.ReadAllText("txt.txt");         
            string[] bits = text.Split(' ');
            int[] numere = Array.ConvertAll(bits, int.Parse);
            

            
            foreach (int item in numere)
            {

                Console.WriteLine(numere[item]);
                
            }
question from:https://stackoverflow.com/questions/65906678/why-do-i-get-an-error-in-the-loop-in-this-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are using the foreach function wrong. In foreach loop you are iterate the items value of the collection each iteration, so the item variable in your case is the value of the cell in that iteration and not his index (like in regular for loop).

It will look like this:

foreach (int item in numere)
{
    Console.WriteLine(item);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...