Search code examples
c#.netlistiteratorstringbuilder

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?


Solution

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