65.9K
CodeProject is changing. Read more.
Home

String concatenation using LINQ to create a CSV/PSV string

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Jun 30, 2011

CPOL
viewsIcon

7862

You can use the Aggregate method with a StringBuilder. I've modified Eric's alternative in order to save a bit of code. Only one return statement is needed as an empty StringBuilder returns an empty string.public static string Join(this IEnumerable parts, string separator) { ...

You can use the Aggregate method with a StringBuilder. I've modified Eric's alternative in order to save a bit of code. Only one return statement is needed as an empty StringBuilder returns an empty string.
public static string Join(this IEnumerable<string> parts, string separator)
       {
           var builder = new StringBuilder();
           if (parts.Any())
           {
               builder.Append(parts.First());
               parts.Skip(1).Aggregate(builder, (sb, s) => sb.Append(separator).Append(s));
           }
           return builder.ToString();
       }