I have been working on a small project and I have ran into this issue. I have a txt file full of lines and I need to store them in a List. Is there any elegant way of doing it? This is my code, however, it won´t work because something is out of bonds. The txt file have 126 lines but I need only 125 of them. Thank you for your time, any help is appreciated :)
string[] Number = System.IO.File.ReadAllLines("Numbers.txt");
List<string> listNumbers = new List<string>(); //place where all numbers will be stored
for (int i = 0; i<125; i++)
{
listNumbers[i] = Number[i];
}
var list = Number.ToList()magicnumbers, just useNumber.LengthorNumber.Length-1(whichever is most appropriate) instead ofi<125List<string>you could create the list directly by usingFile.ReadLines(), e.g.var listNumbers = File.ReadLines("Numbers.txt").Take(125).ToList();forloop. If you're going to loop through an array, use it'sLengthproperty as the upper bounds to avoid anIndexOutOfRangeException:for (int i = 0; i < Number.Length; i++). And if you really do want to restrict the number of items to a maximum of 125, you can just add that to the condition:for (int i = 0; i < Math.Min(Number.Length, 125); i++)