LINQ to append to a StringBuilder from a String[]

后端 未结 4 810
借酒劲吻你
借酒劲吻你 2020-12-17 00:30

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 li

相关标签:
4条回答
  • 2020-12-17 01:03

    If you're using .NET core then this will work:

    stringBuilder.AppendJoin(Environment.NewLine, stringArray);
    

    Although it's not leveraging LINQ, but it does get it done in one line without adding any extra code.

    0 讨论(0)
  • 2020-12-17 01:10
    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);   
        }
    } 
    
    0 讨论(0)
  • 2020-12-17 01:11

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

    stringArray.ToList().ForEach(x => stringBuilder.AppendLine(x));
    

    or

    Array.ForEach(stringArray, x => stringBuilder.AppendLine(x));
    
    0 讨论(0)
  • 2020-12-17 01:17

    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.

    0 讨论(0)
提交回复
热议问题