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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With