Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string.Join() to avoid a trailing comma

Tags:

string

c#

I'm trying to put together a list of email addresses into a string, like this:

string bcc = string.empty
foreach (contact as Contact in contacts)
{
    bcc = bcc + contact.Email + ","
}

The problem with that approach is that the final string has a trailing comma. Not a huge deal, but I'd like to avoid it, just to be tidy. So, I tried this:

bcc = bcc.Join(",", contact.Email);

But that throws an error:

Member 'string.Join(string, params string[])' cannot be accessed with an instance reference; qualify it with a type name instead

So, I tried this:

bcc = String.Join(",", contact.Email);

But that just clears out bcc each time and all I end up with is the last email address. So, I tried this:

bcc = bcc + string.Join(",", contact.Email);

But that gets me a long string of un-delimited emails with no comma separation.

I'm sure when I see the solution, I'll smack my forehead. But I'm not grasping it.

like image 313
Casey Crookston Avatar asked Feb 05 '23 14:02

Casey Crookston


1 Answers

This is what you should use:

// using System.Linq;
bcc = string.Join(",", contacts.Select(c => c.Email));

And then you don't need the foreach anymore, Linq does it for you.

like image 182
Peter B Avatar answered Feb 15 '23 05:02

Peter B