accessing variable outside for loop

一笑奈何 提交于 2020-05-28 08:38:11

问题


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++)
    {
        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


回答1:


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());



回答2:


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());



回答3:


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




回答4:


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.




回答5:


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.




回答6:


String.Join is what you want. You don't have to use a loop.

String.Join(",", yourlist);



回答7:


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); 


来源:https://stackoverflow.com/questions/4639445/accessing-variable-outside-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!