string x;
foreach(var item in collection)
{
x += item+",";
}
can I write something like this with lambdas?
string x;
foreach(var item in collection)
{
x += item+",";
}
can I write something like this with lambdas?
Does this answer your question?
http://stackoverflow.com/questions/21078/whats-the-best-string-concatenation-method-using-c
Note that you can do this with Aggregate
, but the built-in string.Join
is both easier to use and faster for long arrays.
string[] text = new string[] { "asd", "123", "zxc", "456" };
var result = texts.Aggregate((total, str) => total + "," + str);
Shorter syntax, thanks to Earwicker
Assuming C#, have you tried String.Join()? Or is using lambdas mandatory?
Example:
string[] myStrings = ....;
string result = String.Join(",", myStrings);
EDIT
Although the original title (and example) was about concatenating strings with a separator (to which String.Join()
does the best job in my opinion), the original poster seems to ask about the broader solution: how to apply a custom format a list of strings.
My answer to that is write your own method. String.Join has a purpose, reflected by its name (joins some strings). It's high chance that your format logic has a meaning in your project, so write it, give it a proper name and use it.
For instance, if you want to output <li>text</li>
for every item, make something as this:
string FormatAsListItems(string[] myStrings)
{
StringBuilder sb = new StringBuilder();
foreach (string myString in myStrings)
{
sb.Append("<li>").Append(myString).Append("</li>");
}
}
I think the intent is clearer, and you also don't take the performance hit of concatenating strings in a loop.
You are looking too far for the solution. The String
class has a Join
method for this:
string x = String.Join(",", collection);