If you insist on doing it in a LINQy way:
StringBuilder builder = StringArray.Aggregate(
new StringBuilder(),
(sb, s) => sb.AppendLine(s)
);
Alternatively, as Luke pointed out in a comment on another post, you could say
Array.ForEach(StringArray, s => stringBuilder.AppendLine(s));
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))
does not iterate over the StringArray
calling stringBuilder.AppendLine(s)
on each iteration. Rather, it creates an IEnumerable<StringBuilder>
that can be enumerated over.
I suppose that you could say
var e = stringArray.Select(x => stringBuilder.AppendLine(x));
StringBuilder sb = e.Last();
Console.WriteLine(sb.ToString());
but that is really hideous.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…