Saif Khan
Saif Khan

Reputation: 18812

iterating a list with ForEach

I have a list like this

Dim emailList as new List(Of String)
emailList.Add("[email protected]")
emailList.Add("[email protected]")
emaillist.Add("[email protected]")

How can I iterate the list with ForEach to get one string with the emails like this

[email protected];[email protected];[email protected]

Upvotes: 5

Views: 15092

Answers (5)

user26901
user26901

Reputation:

Dim emailList As New StringBuilder()

For Each (email As String In emails)
     emailList.Append(String.Format("{0};", email))
Next

Return emailList.ToString()

Forgive me if there are any syntax errors ... my VB.NET is a little rusty and I don't have a complier handy.

Upvotes: 0

Rich
Rich

Reputation: 121

       Dim emailList As New List(Of String)
    emailList.Add("[email protected]")
    emailList.Add("[email protected]")
    emailList.Add("[email protected]")

    Dim output As StringBuilder = New StringBuilder
    For Each Email As String In emailList
        output.Append(IIf(String.IsNullOrEmpty(output.ToString), "", ";") & Email)
    Next

Upvotes: 2

Gabriel McAdams
Gabriel McAdams

Reputation: 58293

I wouldn't actually use a ForEach loop for this. Here is what I would do:

String.Join(";", emailList.ToArray());

Upvotes: 2

Adriaan Stander
Adriaan Stander

Reputation: 166576

You can try

Dim stringValue As String = String.Join(";", emailList.ToArray)

Have a look at String.Join Method

Upvotes: 2

NebuSoft
NebuSoft

Reputation: 4000

I'm not sure why you would want to use a foreach instead of a String.Join statement. You could simply String.Join() the list using a semi-colon as your joining character.

String.Join(";", emailList.ToArray())

Upvotes: 7

Related Questions