LINQ to append to a StringBuilder from a String[]

人走茶凉 提交于 2019-11-29 04:38:47
jason

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.

Use the "ForEach" extension method instead of "Select".

stringArray.ForEach(x => stringBuilder.AppendLine(x));
vladhorby
stringArray.DoForAll(x => StringBuilder.AppendLine(x));

Where, DoForAll is an extension method:

public static class CommonExtensions 
{ 
    public static void DoForAll<T>(this IEnumerable<T> items, Action<T> action) where T: class 
    { 
        if (action == null) 
            throw new ArgumentNullException("action"); 
        foreach (var item in items) 
            action(item);   
    }
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!