将“列表"项追加到StringBuilder [英] Append 'List' items to StringBuilder
问题描述
我试图用LINQ将List<string>
中的项目附加到StringBuilder
中:
I tried to append the items in a List<string>
to a StringBuilder
with LINQ:
items.Select(i => sb.Append(i + ","));
我在此处找到了类似的问题解释了为什么上述方法不起作用,但是我找不到Each
的Each
或List
上的任何类似内容,我可以代替使用.
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?
推荐答案
您可以使用简单的foreach
循环.这样,您就可以修改StringBuilder的语句,而不是使用带有副作用的表达式.
You could use a simple foreach
loop. That way you have statements which modify the StringBuilder, instead of using an expression with side-effects.
也许String.Join(",", items)
可以更好地解决您的问题.
And perhaps your problem is better solved with String.Join(",", items)
.
这篇关于将“列表"项追加到StringBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!