C#: String Concatenation using StringBuilder and LINQ Aggregate Function


I always forget how to do this so I thought I would post it mainly for my reference.

List<string> nameList = new List<string>() { "Roger", "Clark", "Wonda", "Anita" };

// A useless Select call in this instance just to remind you
// that you coulde use LINQ to select a set of strings
// from a list of objects
StringBuilder names = nameList.Select(n => n)
                              .Aggregate(new StringBuilder(), (current, next) => current.Append(next).Append(", "));

// Remove the trailing comma and space
if (names.Length > 1)
    names.Remove(names.Length - 2, 2);

Console.WriteLine(names.ToString());

// Output
// ------
// Roger, Clark, Wonda, Anita

5 Responses to “C#: String Concatenation using StringBuilder and LINQ Aggregate Function”

  1. Niklas Says:

    How about:
    string names = nameList.Select(n => n).Aggregate((items, item) => items + “, ” + item);

    • Cecil Says:

      Not so good as each “string + string” creates a new string and throws away the old one. Thus the StringBuilder is a better option, at least if there are many list items. If there are only a few list items to concatenate then consider to change your code to
      string names = nameList.Select(n => n).Aggregate((items, item) => String.Format(“{0}, {1}”, items, item));

  2. Bill Says:

    Nice example !

  3. johnwashburn15 Says:

    would
    current.AppendFormat(“, {0}”, next)
    instead of
    current.Append(next).Append(“, “)
    work?

    It
    a) avoids the post processing,
    b) has the efficiency of the string builder
    c) Permits interesting delimiters

  4. sushil Says:

    This can also work

    StringBuilder names = new StringBuilder(nameList.First());
    nameList.Skip(1).Aggregate(names, (c, n) => c.AppendFormat(“,{0}”, n));
    Console.WriteLine(names.ToString());


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: