Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

c# - LINQ to append to a StringBuilder from a String[]

I've got a String array that I'm wanting to add to a string builder by way of LINQ.

What I'm basically trying to say is "For each item in this array, append a line to this StringBuilder".

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

Where as this works:

foreach(String item in stringArray)
{
  stringBuilder.AppendLine(item);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...