LINQ to add to StringBuilder from string []

I have a String array that I want to add to the string builder using LINQ.

Basically I'm trying to say: "For each element in this array, add a string to this StringBuilder."

I can do this quite easily using the foreach loop, however the following code does not seem to do anything. What am I missing?

stringArray.Select(x => stringBuilder.AppendLine(x)); 

Where does it work:

 foreach(String item in stringArray) { stringBuilder.AppendLine(item); } 
+7
stringbuilder c # lambda linq
source share
3 answers

If you insist on doing this 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 Select doesn't work is because Select designed to project and create an IEnumerable projection. So the line of code

 StringArray.Select(s => stringBuilder.AppendLine(s)) 

does not StringArray through a StringArray call that calls stringBuilder.AppendLine(s) at each iteration. Rather, it creates an IEnumerable<StringBuilder> that can be enumerated.

I guess you could say

 var e = stringArray.Select(x => stringBuilder.AppendLine(x)); StringBuilder sb = e.Last(); Console.WriteLine(sb.ToString()); 

but it is really disgusting.

+18
source share

Use the ForEach extension method instead of Select.

 stringArray.ForEach(x => stringBuilder.AppendLine(x)); 
+6
source share

StringArray.DoForAll (x => StringBuilder.AppendLine (x));

0
source share

All Articles