6

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
fearofawhackplanet
  • 52,166
  • 53
  • 160
  • 253

3 Answers3

17
items.ForEach(item => sb.Append(item + ","));
miyamotogL
  • 513
  • 3
  • 10
  • Note that you have to hang on to a List not an IList where this extension is no longer available. That's why I prefer to write my own ForEach that works on IEnumerable. – Tigraine Nov 24 '10 at 12:38
9

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).

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • 3
    I'd completely forgotten about `String.Join`. Sometimes I really need to break out of my Linq wankathon and remember how people programmed before :) – fearofawhackplanet Nov 24 '10 at 12:47
0

Try this:

 String [] items={"Jan","Feb","Mar"};
 StringBuilder sb=new StringBuilder();
 foreach(var entity in items)
 {
   sb.Append(entity + Environment.NewLine);
 }
 Textbox1.Text=sb.tostring();

Output:

Jan

Feb

Mar