1

when I do

String.Join(";", lst.Items)

I get a string of object descriptors instead of item of values. But when I iterate the collection, I end up with a delimiter at the front or back and need to a Substring call afterwards.

    Dim res As String = "" 'or use stringbuilder
    For Each s As String In lst.Items
        s &= ";" & s
    Next
    res = res.Substring(1)

This applies to other cases as well where you want to turn a shared property within a collection into a delimited string. Is there a nice way to do this? Can I do this with LINQ and would it be faster?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
aelgoa
  • 1,193
  • 1
  • 8
  • 24
  • no, ObjectCollections expose already the IList interface, but they contain Objects rather than strings. – aelgoa Oct 11 '13 at 14:17

3 Answers3

3

You'll have to convert the items to strings then:

String.Join(";", lst.Items.Select(Function(item) item.ToString()));
user247702
  • 23,641
  • 15
  • 110
  • 157
  • 2
    +1, but technically, I'd refer to `ToString` as *converting*, not *casting*. `DirectCast` is *casting*. Pretty much everything else in VB.NET, including `CType` and `ToString`, could only be accurately be described as converting. – Steven Doggart Oct 11 '13 at 14:39
  • ty, I picked dbasnett's as the answer cause I expect it to be a bit faster even than LINQ – aelgoa Oct 11 '13 at 21:25
1

How about

    Dim res As String = String.Join(";", lst.Items.OfType(Of String))
dbasnett
  • 11,334
  • 2
  • 25
  • 33
0

This does work:

    Dim col As New Collection
    col.Add("One")
    col.Add("Two")
    col.Add("Three")

    Dim res = String.Join(";", col.OfType(Of String))

See also this question

Community
  • 1
  • 1
dummy
  • 4,256
  • 3
  • 25
  • 36
  • The array is already made, I want to take a property of the elements into a delimited string, without explitl rebuilding – aelgoa Oct 11 '13 at 14:20
  • I added the building of the collection just as an example, because your question didn't contain which kind of collection your question is about. And a Collection is not the same as an array. – dummy Oct 14 '13 at 07:34