Shachaf.Gortler
Shachaf.Gortler

Reputation: 5735

Reformat string to be comma separated and formatted

I have a list of strings...

var strings = new List<String>() { "a", "b", "c" };

I want to output them in a different format, like this:

'a','b','c'

I've tried :

string.Join("','",strings );

and

String.Join(",", String.Format("'{0}'",strings )

Upvotes: 2

Views: 75

Answers (5)

Esperento57
Esperento57

Reputation: 17472

 using System.Linq;

 var result=strings.Select(x=> "'" + x + "'").Aggregate((x, y) => x + "," + y  );

 or 
 var result=string.Format("'{0}'", string.Join("','", strings));

 or
 var result="'" + string.Join("','", strings) + "'";

Upvotes: 0

Neil Barnwell
Neil Barnwell

Reputation: 42155

Your first attempt should work, but you need to prefix and suffix the overall result with "'".

or, you could do:

var strings = new List<string>() { "a", "b", "c" }
                  .Select(x => string.Format("'{0}'", x));

var result = string.Join(",", strings);

Another option is to use a StringBuilder instead,

var strings = new List<string>() { "a", "b", "c" };
var builder = new StringBuilder();

foreach (var s in strings)
{
    builder.AppendFormat(",'{0}'", s);
}

var result = builder.ToString().Trim(",");

In this case I'd recommend the LINQ approach for it's simplicity, but don't rule out the StringBuilder if your real problem is more complex, as it can show the intent of the formatting of each individual item more cleanly.

A hybrid approach where you format the content of each item using a StringBuilder, then build the comma-separated list using LINQ afterwards, could work well.

Upvotes: 2

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

Here is my attempt :)

var result = "'" + string.Join("','", strings) + "'";

or

var result = string.Format("'{0}'", string.Join("','", strings));

Upvotes: 1

Matias Cicero
Matias Cicero

Reputation: 26301

How about:

String.Join(",", strings.Select(s => String.Format("'{0}'", s)));

Upvotes: 2

Joe Farrell
Joe Farrell

Reputation: 3542

You were pretty close with your second attempt. Try this:

string.Join(",", strings.Select(s => $"'{s}'"))

Upvotes: 2

Related Questions