Reputation: 39
When i use for (int i = 1; ..)
skip the loop the first item.
How can i start with index 1 and dont skip any item?
private void buttonReadAndSort_Click(object sender, EventArgs e)
{
ReadFromFile rd = new ReadFromFile();
var fileList = rd.readFromFile();
for (int i = 0; i < fileList.Count; i++)
{
var item = (fileList[i]);
Console.WriteLine(item);
list.Add(item);
listBox1.Items.Add(item);
}
buttonReadAndSort.Enabled = false;
}
Upvotes: 1
Views: 21933
Reputation: 52
List, like array, start at zero. Not sure why you would want it to start it at 1 and not skip any items. I do something like csvLinesPartNumber.Add("stuff")
to add to the list and then I can get "stuff"
from the particular index like so: csvLinesPartNumber[4]
. For example, I am doing a while sqlreader dot read
which will loop through the table with the particular ID. Then you can do another loop to get the data. Just make sure you put the index in the square brackets.
Upvotes: 2
Reputation: 460208
I guess you want to start with index 1 but access the item at index 0:
for (int i = 1; i <= fileList.Count; i++)
{
var item = fileList[i-1];
Console.WriteLine(item);
list.Add(item);
listBox1.Items.Add(item);
}
But you could also loop normally and add +1 where you need it 1 based:
for (int i = 0; i < fileList.Count; i++)
{
var item = fileList[i];
Console.WriteLine("item:{0} #{1}", item, i + 1);
list.Add(item);
listBox1.Items.Add(item);
}
Upvotes: 5