KevinKZ
KevinKZ

Reputation: 159

How to convert a string list into a single list in vb.net?

I am using VS2013 and .NET FrameWork 4.0.

I am building an app that reads a json file and acts upon it.

I have successfully written the code to deserialize the json file and I have a list(of String) which I would like to join in a single string.

This is my code:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim g As GameData = Nothing


    Using fileStream = New System.IO.FileStream("C:\Users\KE-KL\Desktop\Levels\level_0017.json", System.IO.FileMode.Open)
        fileStream.Position = 0
        Dim ser = New System.Runtime.Serialization.Json.DataContractJsonSerializer(GetType(GameData))
        g = DirectCast(ser.ReadObject(fileStream), GameData)
    End Using
        Dim final As String
    final = String.Join(",", g.board.tiles.ToArray)
End Sub

But this line:final = String.Join(",", g.board.tiles.ToArray) creates this error:

Error 1 Overload resolution failed because no accessible 'Join' is most specific for these arguments: 'Public Shared Function Join(Of System.Collections.Generic.List(Of String))(separator As String, values As System.Collections.Generic.IEnumerable(Of System.Collections.Generic.List(Of String))) As String': Not most specific. 'Public Shared Function Join(separator As String, ParamArray values() As Object) As String': Not most specific

Any idea how to fix this? If you need more details, please do ask. Thank you in advance

Upvotes: 0

Views: 2034

Answers (3)

Fabio
Fabio

Reputation: 32455

As your error message said: you trying to pass array of List(Of String) to array of Objects
Try as @Michinarius advised use Aggregate method:

final = g.board.tiles.Aggregate(Of StringBuilder)(New StringBuilder(), _
                                                 Function(temp, val)
                                                     temp.Append(String.Join(",", val))
                                                     Return temp
                                                 End Function).ToString()

Upvotes: 2

JoelC
JoelC

Reputation: 3754

Your problem is that a List(Of List(Of String)) will convert to a multi-dimensional array with the ToArray() call, which String.Join does not handle. Since you have a list of lists, you could do String.Join(",", g.board.titles(0)) and that should work.

Also note that I didn't need the ToArray() call because one of the overrides for join takes an IEnumerable(Of T), which List(Of T) implements.

Upvotes: 1

user3740891
user3740891

Reputation: 33

I think this is because you are trying to join a String (",") and an array (g.board.tiles.ToArray). The Join method doesn't accept String and Array arguments. Choose one or the other, and remember to include an index (or multiple indices for multidimensional arrays) when dealing with specific parts of arrays.

Upvotes: 0

Related Questions