listbox and string concat.
I have
Code:
Dim items = String.Empty
For Each i In ListBox2.Items
items = i & ", " & items
Next
As you can see the string will always END with a comma.
This is fine because when i retrieve the string from the db, i just use the split function.
BUT its something i want to stay away from.
These are the ways I thought of removing it.
1) do some string manipulation and remove the comma at the end.
2) instead of for loop, do a normal loop with a counter. when the counter reaches the last one, throw a if statement and concatenate without the comma.
so whats the best way
Re: listbox and string concat.
Programming does not exist in a vacuum. How would you do this with a pen and paper? Each time you add an item you would add a comma first, except if there were no items already in the list. The same goes here:
vb.net Code:
For Each i In ListBox2.Items
If items <> String.Empty Then
items &= ", "
End If
items &= i
Next i
Note that that will get the list in the opposite order to what you currently have. If that's an issue then use a For instead of a For Each loop and work backwards.
Re: listbox and string concat.
Quote:
Originally Posted by jmcilhinney
Programming does not exist in a vacuum. How would you do this with a pen and paper? Each time you add an item you would add a comma first, except if there were no items already in the list. The same goes here:
vb.net Code:
For Each i In ListBox2.Items
If items <> String.Empty Then
items &= ", "
End If
items &= i
Next i
Note that that will get the list in the opposite order to what you currently have. If that's an issue then use a For instead of a For Each loop and work backwards.
Thanks for that.
Works perfectly.
Re: listbox and string concat.
I meant to mention in my previous post, I'd also recommend using a StringBuilder rather than String concatenation. That is especially true if you have a lot of items in your ListBox. Each time you use a concatenation operator (&) a new String object is created and the contents of the two operands copied into it. That makes for a lot of memory allocation and data copying very quickly, which is very inefficient. The StringBuilder is far more optimal for building strings.