232

Lets say you have a:

List<string> los = new List<string>();

In this crazy functional world we live in these days which one of these would be best for creating one string by concatenating these:

String.Join(String.Empty, los.ToArray());

StringBuilder builder = new StringBuilder();
los.ForEach(s => builder.Append(s));

string disp = los.Aggregate<string>((a, b) => a + b);

or Plain old StringBuilder foreach

OR is there a better way?

1

6 Answers 6

323

I would go with option A:

String.Join(String.Empty, los.ToArray());

My reasoning is because the Join method was written for that purpose. In fact if you look at Reflector, you'll see that unsafe code was used to really optimize it. The other two also WORK, but I think the Join function was written for this purpose, and I would guess, the most efficient. I could be wrong though...

As per @Nuri YILMAZ without .ToArray(), but this is .NET 4+:

String.Join(String.Empty, los);
7
  • GA! I didn't even see this option at first- read right past it. Nov 25, 2008 at 20:47
  • 2
    3 times faster than the StringBuilder? Wow, I figured it would be faster, didn't realize just how much faster. It makes sense though, it's done in unsafe code using pointers, so..... makes sense.
    – BFree
    Nov 25, 2008 at 21:01
  • 8
    nice! only remark: Join doesn't need los.ToArray(), because List<T> can cast IEnumarable<T>. Mar 10, 2011 at 19:40
  • 8
    @Nuri: This question was asked in 08, before .Net 4 was out. The overload that takes IEnumerable<T> was added in .Net 4.
    – BFree
    Mar 10, 2011 at 20:15
  • 2
    String.Join in conjunction with String.Concat is golden. Ex: 'String.Concat( "{ ", String.Join( ", ", m_Data ), " }" );'
    – KornMuffin
    Oct 21, 2011 at 16:01
55
string.Concat(los.ToArray());

If you just want to concatenate the strings then use string.Concat() instead of string.Join().

1
  • I think this should be the accepted answer. Nov 8, 2021 at 15:53
19

If you use .net 4.0 you can use a sorter way:

String.Join<string>(String.Empty, los);
10

String.Join() is implemented quite fast, and as you already have a collection of the strings in question, is probably the best choice. Above all, it shouts "I'm joining a list of strings!" Always nice.

10
los.Aggregate((current, next) => current + "," + next);
5

My vote is string.Join

No need for lambda evaluations and temporary functions to be created, fewer function calls, less stack pushing and popping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.