Convert Dictionary into structured format string

GoldBishop picture GoldBishop · Nov 28, 2012 · Viewed 11k times · Source

I have a Dictionary object declared as var as Dictionary(of String, String).

I am trying to utilize the LINQ extensions available to the Generic Collection but am only getting the non-extension methods.

I need to turn the Dictionary collection into a string with the following pattern: key1=val1, key2=val2, ..., keyn=valn

Thought at first doing a foreach loop would hit the spot except the fact that i am programmers-block.

What i have so far, but doubt its the best logic pattern for producing this:

Public Overrides Function ToString() As String
    Dim ret As String = ""
    For Each kv As KeyValuePair(Of String, String) In Me._set
        If ret <> String.Empty Then
            ret &= ", "
        End If

        ret &= String.Format("{0}={1}", kv.Key, kv.Value)
    Next

    Return ret
End Function

And for some reason even though i have imported the System.Core & System.Linq libraries into the project none of the extended LINQ extensions are showing up in my dev-env intellisense. So for now, unless someone could help me get the LINQ extensions to show up in Intellisense, they are out of the question.

Found the problem with the LINQ extensions not showing up, so they are back on the table ;)

Answer

jbl picture jbl · Nov 28, 2012

I would have written the whole method block with Linq like this (sorry for the C#-vb.net soup...)

c-sharp

return String.Join(",",Me._set.Select(kvp=>String.Format("{0}={1}",kvp.Key, kvp.Value).ToArray());

Also, I don't really know what _set is. Maybe you'll have to cast :

c-sharp:

return String.Join(",", Me._set.Cast<KeyValuePair<String,String>>().Select(kvp=>String.Format("{0}={1}",kvp.Key, kvp.Value).ToArray());

vb.net:

return String.Join(", ", Me.Select(Function(kvp) String.Format("{0}={1}", kvp.Key, kvp.Value)).ToArray())

Hope this will help,