0

How to use the string builder AppendFormat dynamically. My code below shows an error. How do that correctly in MVC c#?

Code:

var s = new StringBuilder();
s.AppendFormat("\"{0}\",\"{1}",
                     "test1",
                     "test2"
                              );
for(var i = 2; i < 10 ; i++)
{
     s.AppendFormat(",\"{"+i+"}\"",  "loop"); // error shows here
}
tereško
  • 58,060
  • 25
  • 98
  • 150
US_User
  • 57
  • 1
  • 6
  • You are trying to build a format string with string formatting? Does that sound wrong? If you already have the data, just build the string directly. – Jodrell Sep 24 '13 at 11:44
  • if your really wan tto do this, which your shouldn't, look as this question and answer http://stackoverflow.com/questions/91362/how-to-escape-brackets-curly-braces-in-a-format-string-in-net. – Jodrell Sep 24 '13 at 11:45

3 Answers3

1

You don't have to put a new index for each loop into the AppendFormat, simply use

        var s = new StringBuilder();
        s.AppendFormat("\"{0}\",\"{1}",
                            "test1",
                            "test2"
                                     );
        for (var i = 2; i < 10; i++)
        {
            s.AppendFormat(",\"{0}\"", "loop"); 
        }
MichaC
  • 13,104
  • 2
  • 44
  • 56
0

Whenever you are using the AppendFormat it should start with 0.

Try this.

var s = new StringBuilder();
s.AppendFormat("\"{0}\",\"{1}",
                 "test1",
                 "test2"
   );
for(var i = 2; i < 10 ; i++)
{
 s.AppendFormat(",\"{0}\"",  "loop");  
}  

If you need to have dynamic counter then this would be work around.

var s = new StringBuilder();
var s1 = new StringBuilder();
string[] _d = new string [10];
s.AppendFormat("\"{0}\",\"{1}",
               "test1",
               "test2"
              );
for(var i = 0; i < 10 ; i++)
{
     s1.Append(",\" Loop {"+i+"}\"");
    _d[i] = i.ToString();
}
s.AppendFormat(s1.ToString(), _d);
Aravinth Kannan
  • 535
  • 6
  • 8
0

this will do what you want but, just build what you want in the first place, rather than do 2 formats.

var format = new StringBuilder();
format.Append("\"{0}\",\"{1}\"");
for(var i = 2; i < 10 ; i++)
{
    format.AppendFormat(",\"{{{0}}}\"",  i);
}

then you can do,

var result = string.Format(
    format.ToString(),
    "test1",
    "test2",
    "loop",
    "loop",
    "loop",
    "loop",
    "loop",
    "loop",
    "loop",
    "loop",
    "loop");
Jodrell
  • 34,946
  • 5
  • 87
  • 124