Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to place a comma after each word but the last in the list

Tags:

c#

I totally new to C# and learning as I go. I am stuck on issue which I'm hoping an experienced programmer can help. I have added a CheckedListBox to my form and added a collection of 6 items to it. I need all but the last item selected to have a comma placed beside it, so my question is: how can I tell C# NOT to place a comma beside the last item selected?

foreach (object itemChecked in RolesCheckedListBox.CheckedItems)
{
    sw.Write(itemChecked.ToString() + ",");
}

Thanks for any help received! Dan

like image 277
Dan Ergis Avatar asked Sep 06 '25 18:09

Dan Ergis


1 Answers

It can be done using string.Join() method:

string commaSeparated = string.Join(",", 
                RolesCheckedListBox.CheckedItems.Select(item => item.ToString());

For example:

string[] names = new []{ "a", "b"};
string separatedNames = string.Join(",", names);

Will result that separatedNames will be "a,b"

like image 88
Elisha Avatar answered Sep 11 '25 03:09

Elisha