问题
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 )
回答1:
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.
回答2:
You were pretty close with your second attempt. Try this:
string.Join(",", strings.Select(s => $"'{s}'"))
回答3:
How about:
String.Join(",", strings.Select(s => String.Format("'{0}'", s)));
回答4:
Here is my attempt :)
var result = "'" + string.Join("','", strings) + "'";
or
var result = string.Format("'{0}'", string.Join("','", strings));
回答5:
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) + "'";
来源:https://stackoverflow.com/questions/38404988/reformat-string-to-be-comma-separated-and-formatted