1

I'm adding values from a file to an array and then adding those values to a list box in a form. I have methods performing calculations and everything is working great, but I'd like to be able to use a loop and insert the year prior to the values I am inserting into the list box. Is there a way to use the .Add method and include a variable which will be changing in this? Something like populationListbox.Items.Add(i, value); if i is my loop counter? Code is below so I'd like first line in the list box to have the year I specify with my counter, followed by the population. Like this, "1950 - 151868". As of now it only displays the value 151868. Thanks!

const int SIZE = 41;
int[] pops = new int[SIZE];
int index = 0;
int greatestChange;
int leastChange;
int greatestYear;
int leastYear;
double averageChange;
StreamReader inputFile;


inputFile = File.OpenText("USPopulation.txt");


while (!inputFile.EndOfStream && index < pops.Length)
{
    pops[index] = int.Parse(inputFile.ReadLine());
    index++;
}

inputFile.Close();



foreach (int value in pops)
{
    **populationListbox.Items.Add(value);**
}

greatestChange = greatestIncrease(pops) * 1000;
leastChange = leastIncrease(pops) * 1000;
averageChange = averageIncrease(pops) * 1000;
greatestYear = greatestIncreaseyear(pops);
leastYear = leastIncreaseyear(pops);

greatestIncreaselabel.Text = greatestChange.ToString("N0");
leastIncreaselabel.Text = leastChange.ToString("N0");
averageChangelabel.Text = averageChange.ToString("N0");
greatestIncreaseyearlabel.Text = greatestYear.ToString();
leastIncreaseyearlabel.Text = leastYear.ToString();

1 Answer 1

2

Like this?

int i = 1950;

foreach (int value in pops)
{
   populationListbox.Items.Add(i.ToString() + " - " + value);
   i++;
}

Your life will be a lot easier if you stop trying to program C# as if it were 1980s C and use the power of it's Framework:

var pops = File.ReadLines("USPopulation.txt").Select(int.Parse);

populationListbox.Items.AddRange(pops.Select((p,i) => $"{i} - {p}"));
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. That's exactly what I was looking for. Was having trouble with the syntax. Yeah this is an assignment so we have to put in what he's been teaching us. :) Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.