简体   繁体   中英

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 )

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

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

怎么样:

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

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.

Here is my attempt :)

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

or

var result = string.Format("'{0}'", string.Join("','", strings));
 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) + "'";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM