LINQ从String []追加到StringBuilder [英] LINQ to append to a StringBuilder from a String[]
问题描述
我有一个String数组,我想通过LINQ添加到字符串生成器中.
I've got a String array that I'm wanting to add to a string builder by way of LINQ.
我基本上要说的是对于此数组中的每个项目,在此StringBuilder后面添加一行".
What I'm basically trying to say is "For each item in this array, append a line to this StringBuilder".
我可以使用foreach循环很容易地做到这一点,但是下面的代码似乎什么也没做.我想念什么?
I can do this quite easily using a foreach loop however the following code doesn't seem to do anything. What am I missing?
stringArray.Select(x => stringBuilder.AppendLine(x));
在什么地方起作用:
foreach(String item in stringArray)
{
stringBuilder.AppendLine(item);
}
推荐答案
如果您坚持以LINQy方式这样做:
If you insist on doing it in a LINQy way:
StringBuilder builder = StringArray.Aggregate(
new StringBuilder(),
(sb, s) => sb.AppendLine(s)
);
或者,如 Luke 在另一篇文章的评论中指出的,你可以说
Alternatively, as Luke pointed out in a comment on another post, you could say
Array.ForEach(StringArray, s => stringBuilder.AppendLine(s));
Select
不起作用的原因是,Select
用于投影并创建投影的IEnumerable
.所以这行代码
The reason that Select
does not work is because Select
is for projecting and creating an IEnumerable
of the projection. So the line of code
StringArray.Select(s => stringBuilder.AppendLine(s))
不会在每次迭代中遍历StringArray
调用stringBuilder.AppendLine(s)
的情况.而是创建一个可以枚举的IEnumerable<StringBuilder>
.
does not iterate over the StringArray
calling stringBuilder.AppendLine(s)
on each iteration. Rather, it creates an IEnumerable<StringBuilder>
that can be enumerated over.
我想你可以说
var e = stringArray.Select(x => stringBuilder.AppendLine(x));
StringBuilder sb = e.Last();
Console.WriteLine(sb.ToString());
但这真的很可怕.
这篇关于LINQ从String []追加到StringBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!