Convert Dictionary into structured format string

南楼画角 提交于 2019-12-10 03:00:43

问题


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 ;)


回答1:


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,




回答2:


As far as your non-LINQ loop goes, I would recommend doing it like this:

Public Overrides Function ToString() As String
    Dim items As New List(Of String)(_set.Count)
    For Each pair As KeyValuePair(Of String, String) In _set
        items.Add($"{pair.Key}={pair.Value}"))
    Next
    Return String.Join(", ", items)
End Function

With LINQ, you could do it like this:

Public Overrides Function ToString() As String
    Return String.Join(", ", _set.Select(Function(pair) $"{pair.Key}={pair.Value}"))
End Function



回答3:


VB.net syntax:

Dim dic As New Dictionary(Of String, String)() From {
            {"a", "1"},
            {"b", "2"},
            {"c", "3"},
            {"d", "4"}
            }

Dim s As String = String.Join(",", dic.Select(Function(pair) String.Format("{0}={1}", pair.Key, pair.Value)).ToArray())


来源:https://stackoverflow.com/questions/13610071/convert-dictionary-into-structured-format-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!