1

This has to be an easy question, but I cannot figure out how to create a list of names separated by commas without having a trailing comma at the end.

So here is my code...

    For Each u In users
        userList.Append(u.FirstName)
        userList.Append(" ")
        userList.Append(u.LastName)
        userList.Append(", ")
    Next

This creates a list, but it always looks likes this:

James Smith, Chris Williams, Zoey Babcock,

How do I get generate a list without an extra comma at the end?

Thanks

Here is the working code thanks to all the help:

    Dim fullNames = (users.Select(Function(u) u.FirstName + " " + u.LastName))
    Dim userList As String = String.Join(", ", fullNames)
1

3 Answers 3

3

You can use LINQ to project each user into a collection of full names, then use String.Join() to join them using a separator of your choice.

List(Of String) fullNames = From u _
                            In users _
                            Select (u.FirstName + " " + u.LastName)
String userList = String.Join(", ", fullNames)

You can express the LINQ query like this as well. It is identical to the above:

List(Of String) fullNames = _
                users.Select(Function(u) u.FirstName + " " + u.LastName)
String userList = String.Join(", ", fullNames)
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think I've ever seen code like this before...what is this style called and what does this code do? - thanks -
It's called LINQ as in Language INtegrated Query and can do some neat tricks. I Updated my answer and added a link.
great, I've heard of it before but didn't realize it was so powerful. thanks!
2
For i as integer = 0 to users.Count - 1
    userList.Append(String.Format("{0} {1}", users(i).FirstName, users(i).LastName))
    If (i + 1) < users.Count - 1
        userList.Append(", ")
    End If
Next 

Comments

1

LINQ and Join is the best answer when it is available, but otherwise you should be using StringBuilder and then it is easiest to leave your code as it is, with the following final line:

If userList.Length > 0 Then userList.Length -= ", ".Length
Return userList.ToString

Comments

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.