1

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.

8
  • And what problem did you get with that code? Commented Sep 3, 2018 at 13:28
  • You really want your string to start with ,? Commented Sep 3, 2018 at 13:30
  • "I think I can't make the logic" What is the logic? Commented Sep 3, 2018 at 13:30
  • @Magnus it doesn't Commented Sep 3, 2018 at 13:30
  • @J.vanLangen no? ,'abc','avc',abc...... Commented Sep 3, 2018 at 13:31

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

More simple with LinQ and method Join

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.