Is there a simple way to create a comma delimited string from a list of items without adding an extra ", " to the end of the string?
I frequently need to take an ASP.NET CheckBoxList and format the selected values as a string for insertion into an e-mail. It's straightforward to loop over the selected checkboxes, get the values, and add them to a StringBuilder with a ", " separating them, but the Count property returns the number of items in the list total, not the number of items that are actually selected. So it's hard to know when you've reached the last item, and you end up with a stray ", " on the end.
I've played around with several different approaches to this problem. Lately I've been doing something like this:
private string ConcatenateCheckBoxListItems()
{
StringBuilder sb = new StringBuilder();
char[] characters = new char[] {" ", ","};
String trimmedString;
foreach (ListItem item in MyList)
{
sb.Append(item.Value + ", ");
}
trimmedString = sb.ToString().TrimEnd(characters);
return trimmedString;
}
But it's definitely clunky. So do the various for loop approaches I've tried. Any suggestions for a cleaner implementation?
delimiter.ToCharArray()
in order to make maintenance just a tad bit easier. \$\endgroup\$