Given a list of strings, what is the best method for concatenating these strings into a comma separated list with no comma at the end. (VB.NET or C#) (Using either StringBuilder
Like this:
lstItems.ToConcatenatedString(s => s, ", ")
If you want to ignore empty strings as in your example:
lstItems
.Where(s => s.Length > 0)
.ToConcatenatedString(s => s, ", ")
The most popular custom aggregate function in my toolbox. I use it every day:
public static class EnumerableExtensions
{
///
/// Creates a string from the sequence by concatenating the result
/// of the specified string selector function for each element.
///
public static string ToConcatenatedString(
this IEnumerable source,
Func stringSelector)
{
return EnumerableExtensions.ToConcatenatedString(source, stringSelector, String.Empty);
}
///
/// Creates a string from the sequence by concatenating the result
/// of the specified string selector function for each element.
///
/// The string which separates each concatenated item.
public static string ToConcatenatedString(
this IEnumerable source,
Func stringSelector,
string separator)
{
var b = new StringBuilder();
bool needsSeparator = false; // don't use for first item
foreach (var item in source)
{
if (needsSeparator)
b.Append(separator);
b.Append(stringSelector(item));
needsSeparator = true;
}
return b.ToString();
}
}