Reputation: 153
I want to generate a string with a format
'abc','avc',abc','avc',abc','avc','abc','avc',abc','avc',abc','avc','abc','avc'
The value can be anything or it can be empty.This is my code
string sep = "";
StringBuilder sb = new StringBuilder();
foreach(var l in label.Rows)
{
sb.Append(sep).Append(l.Text);
sep = ",''";
}
this returns me
abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc
any help will be appreciated.
Upvotes: 1
Views: 84
Reputation: 216293
Of course using Linq will be simpler and more readable, but if you want to know what has gone wrong in your code then
// Start with the initial quote
string sep = "'";
StringBuilder sb = new StringBuilder();
foreach(var l in label.Rows)
{
sb.Append(sep).Append(l.Text);
// Quote before and after the comma
sep = "','";
}
// You need an additional quote to close the string if there is any
if(sb.Length > 0)
sb.Append("'");
Consider also that StringBuilder is not always faster than a simple concatenation. If this code is performance sensitive I would try to measure what happen if you use a single sb.Append(sep + l.Text) instead of calling two times the Append method
Upvotes: 4