Append 'List' items to StringBuilder

我的梦境 提交于 2020-01-14 20:19:10

问题


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?


回答1:


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




回答2:


items.ForEach(item => sb.Append(item + ","));



回答3:


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



来源:https://stackoverflow.com/questions/4266795/append-list-items-to-stringbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!