What is the most efficient way to write the old-school:
StringBuilder sb = new StringBuilder();
if (strings.Count > 0)
{
foreach (string s in strings)
{
sb.Append(s + ", ");
}
sb.Remove(sb.Length - 2, 2);
}
return sb.ToString();
...in LINQ?
I'm going to cheat a little and throw out a new answer to this that seems to sum up the best of everything on here instead of sticking it inside of a comment.
So you can one line this:
Edit: You'll either want to check for an empty enumerable first or add an
.Replace("\a",string.Empty);
to the end of the expression. Guess I might have been trying to get a little too smart.The answer from @a.friend might be slightly more performant, I'm not sure what Replace does under the hood compared to Remove. The only other caveat if some reason you wanted to concat strings that ended in \a's you would lose your separators... I find that unlikely. If that is the case you do have other fancy characters to choose from.
Why use Linq?
That works perfectly and accepts any
IEnumerable<string>
as far as I remember. No needAggregate
anything here which is a lot slower.Here it is using pure LINQ as a single expression:
And its pretty damn fast!
You can combine LINQ and
string.join()
quite effectively. Here I am removing an item from a string. There are better ways of doing this too but here it is:Have you looked at the Aggregate extension method?
In .Net 4, there's a new overload for
string.Join
that acceptsIEnumerable<string>
. The code would then look like: