c# - Reformat string to be comma separated and formatted -
i have list of strings...
var strings = new list<string>() { "a", "b", "c" };
i want output them in different format, this:
'a','b','c'
i've tried :
string.join("','",strings );
and
string.join(",", string.format("'{0}'",strings )
your first attempt should work, need prefix , suffix overall result "'"
.
or, do:
var strings = new list<string>() { "a", "b", "c" } .select(x => string.format("'{0}'", x)); var result = string.join(",", strings);
another option use 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 case i'd recommend linq approach it's simplicity, don't rule out stringbuilder
if real problem more complex, can show intent of formatting of each individual item more cleanly.
a hybrid approach format content of each item using stringbuilder
, build comma-separated list using linq afterwards, work well.
Comments
Post a Comment