Alex Rivera | Logout

List of strings to one string

Asked 2008-11-25T20:38:05.000
235

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?

Edit
Report

2 Answers

327

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);
answered 2008-11-25T20:42:51.153
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.

answered 2008-11-25T20:42:54.740

Your Answer