foreach loop and array values
I am writing a simple foreach loop to read key values from appconfig file. For some reason the array string called server looses previous values each time the foreach loop increments. Once the program runs to completion I see values as (server[0] = null, server[1]=null, server[2] = ). Only the last array pointer server[3] retains the values.
My questions are:
How can I retain all the array values and pass them outside the foreach loop?
private void button2_Click(object sender, EventArgs e)
{
int i = 0;
int max = 0;
string[] server;
foreach (string key in System.Configuration.ConfigurationManager.AppSettings)
{
max = max + 1;
}
foreach (string key in System.Configuration.ConfigurationManager.AppSettings)
{
server = new string[max];
server[i] = key;
MessageBox.Show(server[i]).ToString();
i = i + 1;
}
}
server = new string[max];
Should be outside the loop (in your case, between the two), otherwise you create a new array every iteration. This explains why the last value is correct, and the rest are empty.
Also, you can use ++
instead of i + 1
and max + 1
.
Evan说的 - 同样,考虑使用LINQ来使你的代码更具可读性,并避免类似的错误:
var server = System.Configuration.ConfigurationManager.AppSettings
.Cast<string>().ToList();
foreach (string key in server)
MessageBox.Show(key);
Evan is exactly right. In addition to that, I recommend replacing the first foreach loop with
max = System.Configuration.ConfigurationManager.AppSettings.Count;
链接地址: http://www.djcxy.com/p/52750.html
上一篇: 更改List <T>中的某个值
下一篇: foreach循环和数组值