HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Comma delimited string from list of items

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
commadelimiteditemslistfromstring

Problem

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?

Solution

string.Join() is a good answer, but I prefer to create an extension method:

namespace StringExtensions
{
    static class _
    {
        public static string JoinString(this IEnumerable source, string seperator = "")
        {
            return string.Join(seperator, source);
        }
    }
}


which is used like this:

return MyList.Select(i => i.Value).JoinString(", ");


(I'm using my unconventional method of organizing extension methods, which you can read about here: http://jbazuzicode.blogspot.com/2009/01/way-to-manage-extension-methods-in-c.html).

Code Snippets

namespace StringExtensions
{
    static class _
    {
        public static string JoinString<T>(this IEnumerable<T> source, string seperator = "")
        {
            return string.Join(seperator, source);
        }
    }
}
return MyList.Select(i => i.Value).JoinString(", ");

Context

StackExchange Code Review Q#1122, answer score: 5

Revisions (0)

No revisions yet.