fedeteka fedeteka - 3 months ago 14
Vb.net Question

How to get rid of the first concatenation symbol

I'm looping a table database to catch the first name of some rows

The code is like:

Try
While (readerFirstName.Read())
SearchedName = readerFirstName("parteA")
CombinatedNames = CombinatedNames & " & " & SearchedName
End While

Catch ex As Exception
MsgBox(ex.ToString())
End Try


And the desired result si something like

Mike & Eric & Tom

but I get

& Mike & Eric & Tom

I think I can get rid of the first " &" after the string formation using String.TrimStart

but there's a better way to cut the first "& "?

Answer

Try replacing your loop:

While (readerFirstName.Read())
    SearchedName = readerFirstName("parteA")
    CombinatedNames = CombinatedNames & " & " & SearchedName
End While

With this one:

Dim names As New List(Of String)()
While (readerFirstName.Read())
    names.Add(readerFirstName("parteA"))
End While
CombinatedNames = String.Join(" & ", names)

The main idea here is to use the String.Join method to concatenate the single names in one single operation. That method acts on collections, so you will first have to read the single items into a collection names.

This method will take care to add the separator string " & " between items, never before the first or after the last, so you will not end up with a leading or trailing separator (unless you have an empty item in your list).

P.S.: If you happen to know beforehand how many names will be read from readerFirstNames, you could optimise memory usage of my suggested code by passing the name count to the List(Of T) constructor (as the capacity parameter).