从数组WITH文本向列表框添加值

时间:2016-10-27 19:27:43

标签: c# arrays list

我正在将文件中的值添加到数组中,然后将这些值添加到表单中的列表框中。我有方法执行计算,一切都很好,但我希望能够使用循环并插入我插入列表框中的值之前的年份。有没有办法使用.Add方法并包含一个将在此更改的变量?如果populationListbox.Items.Add(i, value);是我的循环计数器,那么像i这样的东西?代码在下面所以我想在列表框中的第一行有我用计数器指定的年份,然后是人口。像这样,“1950 - 151868”。截至目前,它只显示值151868.谢谢!

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 个答案:

答案 0 :(得分:2)

喜欢这个吗?

int i = 1950;

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

如果你停止尝试将C#编程为1980年代的C并使用它的强大功能,你的生活将变得更加容易:

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

populationListbox.Items.AddRange(pops.Select((p,i) => $"{i} - {p}"));