Shanto Siddiq
Shanto Siddiq

Reputation: 153

Concatenating string with String Builder?

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

Answers (2)

Steve
Steve

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

Antoine V
Antoine V

Reputation: 7204

More simple with LinQ and method Join

string s = string.Join(",", label.Rows.Select(l => $"'{l.Text}'"));

Upvotes: 3

Related Questions