accessing variable outside for loop
how to access a string assigned some value in a for loop, outside the for loop i may provide you with the code for thy convenience
for (Int32 i = 0; i < yourlist.Count; i++)
{
开发者_如何学Go String str=(yourlist[i].ToString() + ",");
}
String str1 = (str).Substring(0, str.Length - 1);
the error displayed is
The name 'str' does not exist in the current context
The scope of the variable does not extend to outside the loop. If you want to access its value, you need to save it to another variable with a greater scope, like this:
string str;
for (Int32 i = 0; i < yourlist.Count; i++)
{
str=(yourlist[i].ToString() + ",");
}
String str1 = (str).Substring(0, str.Length - 1);
However, what you are trying to do can be simply done as:
var str1 = string.Join(",", yourlist.Select(o => o.ToString()).ToArray());
When you declare a variable inside a for
loop (or any other scope), it doesn't exist outside of that scope.
You need to declare the variable outside of the loop.
Note that this won't do what you want it to do, since you aren't appending the string.
Instead, you should use a StringBuilder.
You can make it somewhat simpler by only appending ", "
if i > 0
.
In .Net 4.0, you can replace your entire loop with a new overload of String.Join
:
string str1 = String.Join(", ", yourlist);
Before .Net 4.0, you can replace it with
string str1 = String.Join(", ", yourlist.Select(o => o.ToString()).ToArray());
String str = string.Empty;
for (Int32 i = 0; i < yourlist.Count; i++)
{
str=(yourlist[i].ToString() + ",");
}
String str1 = (str).Substring(0, str.Length - 1);
Also you may want to store the result back to str variable
str = (str).Substring(0, str.Length - 1);
In such case you dont need to declare one more variable
Declare the variable str before the loop starts.because the variable str declared inside the for loop goes out of scope and hence is an error in compilation.
String str;
for (int i = 0; i < yourlist.Count; i++)
{
str = (yourlist[i].ToString() + ",");
}
str1 = str.Substring(0, str.Length - 1);
But the better way to write this code is:
str1 = string.Join(",", yourlist);
Although "str" and "str1" are really bad names for variables. They don't mean anything. A variable name should have a clue to what this variable stores, and not to its datatype.
String.Join is what you want. You don't have to use a loop.
String.Join(",", yourlist);
Try the code below:
String str = "";
for (Int32 i = 0; i < yourlist.Count; i++)
{
str =(yourlist[i].ToString() + ",");
}
String str1 = (str).Substring(0, str.Length - 1);
精彩评论