Problem
Assume you have a:
List<string> los = new List<string>();
Which of these, in today’s crazy functional world, would be the best for concatenating these into a single string:
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);
alternatively a simple foreach loop with StringBuilder
Is there a better option?
Asked by maxfridbe
Solution #1
Option A is the one I would choose:
String.Join(String.Empty, los.ToArray());
My reasoning is that the Join method was created specifically for this purpose. In fact, if you look at Reflector, you’ll notice that unsafe code was utilized to maximize performance. The other two WORK as well, but I believe the Join function was created specifically for this purpose and is, therefore, the most efficient. However, I could be mistaken…
Without.ToArray(), as per @Nuri YILMAZ, but this is.NET 4+:
String.Join(String.Empty, los);
Answered by BFree
Solution #2
string.Concat(los.ToArray());
Use string if you merely want to concatenate the strings. Instead of string, use Concat(). Join().
Answered by Pent Ploompuu
Solution #3
If you’re using.net 4.0, you can use the following method:
String.Join<string>(String.Empty, los);
Answered by mnieto
Solution #4
String. Join() is a fast method that is usually the best choice because you already have a collection of the strings in question. Above all, it exclaims, “I’m joining a string list!” Always a pleasure.
Answered by J Cooper
Solution #5
los.Aggregate((current, next) => current + "," + next);
Answered by landrady
Post is based on https://stackoverflow.com/questions/318756/list-of-strings-to-one-string