Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append 'List' items to StringBuilder

I tried to append the items in a List<string> to a StringBuilder with LINQ:

items.Select(i => sb.Append(i + ","));

I found a similar question here which explains why the above doesn't work, but I couldn't find an Each of ForEach or anything similar on List which I could use instead.

Is there a neat way of doing this in a one-liner?

like image 658
fearofawhackplanet Avatar asked Nov 24 '10 12:11

fearofawhackplanet


People also ask

What is append in StringBuilder append?

StringBuilder. append(boolean a) is an inbuilt method in Java which is used to append the string representation of the boolean argument to a given sequence. Syntax : public StringBuilder append(boolean a) Parameter: This method accepts a single parameter a of boolean type and refers to the Boolean value to be appended.

Can we append integer to StringBuilder?

append(int i) method appends the string representation of the int argument to this sequence.

How does StringBuilder append work?

append(String str) method appends the specified string to this character sequence. The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument.

How use append method in C#?

Add/Append String to StringBuilderUse the Append() method to append a string at the end of the current StringBuilder object. If a StringBuilder does not contain any string yet, it will add it. The AppendLine() method append a string with the newline character at the end.


2 Answers

items.ForEach(item => sb.Append(item + ","));
like image 197
miyamotogL Avatar answered Oct 07 '22 13:10

miyamotogL


You could use a simple foreach loop. That way you have statements which modify the StringBuilder, instead of using an expression with side-effects.

And perhaps your problem is better solved with String.Join(",", items).

like image 39
CodesInChaos Avatar answered Oct 07 '22 12:10

CodesInChaos