Comma delimited string from list of items

  • 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?


    Does this built-in do what you want?

    Despite the answers, in this code, your delimiter should be a string, and trim end should call `delimiter.ToCharArray()` in order to make maintenance just a tad bit easier.

  • pdr

    pdr Correct answer

    10 years ago

    Would this not suffice?



    private string ConcatenateCheckBoxListItems()
    {
    return string.Join(", ", from item in MyList select item.Value);
    }

    Cool, how didn't I know that one. :O :)

    @Steven That's the thing with the .NET Framework. You can't know it all; you only know what you've had to know. And that's why sites like this exist.

    I absolutely love this site. Yes, that's perfect, compact, elegant... I feel like more of a novice every day. :)

    Does this take care of escaping your list values from any contained ',' characters ?

    @thedev No, but it could easily be extended for that. Simply change the bit after select to either replace commas `item.Value.Replace(",", @"\,")` or surround the string in quotes `item.Value.Contains(",") ? string.Format(@"""{0}""", item.Value) : item.Value`. Whatever you require

    Python? In *my* C#? In all seriousness, I didn't know you could do such wizardry in C#. Great answer.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used