5

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.

1
  • Just to add to Peter B, you use the Join (a static method) on string class not bcc instance. Commented Dec 6, 2016 at 17:07

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

Comments

-2

Adding to @Peter's answer, and from this you can join then trim last comma:

bcc = string.Join(",", contacts.Select(c => c.Email)).TrimEnd(',');

2 Comments

No need to trim the last comma, Join doesn't add that
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.