7

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?

2
  • What version of .Net are you using? ForEach is a method on the generic list in .Net 4. Commented Nov 24, 2010 at 12:39
  • yes I'm .Net 3.5 unfortunately Commented Nov 24, 2010 at 12:40

3 Answers 3

17
items.ForEach(item => sb.Append(item + ","));
Sign up to request clarification or add additional context in comments.

1 Comment

Note that you have to hang on to a List<T> not an IList<T> where this extension is no longer available. That's why I prefer to write my own ForEach that works on IEnumerable<T>.
10

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

1 Comment

I'd completely forgotten about String.Join. Sometimes I really need to break out of my Linq wankathon and remember how people programmed before :)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.