将字典转换为结构化格式的字符串 [英] Convert Dictionary into structured format string

查看:204
本文介绍了将字典转换为结构化格式的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Dictionary对象声明为 var作为Dictionary(of String,String)

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

我是试图利用可用于Generic Collection的LINQ扩展,但只得到了非扩展方法。

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

我需要将Dictionary集合转换为具有以下模式的字符串: key1 = val1,key2 = val2,...,keyn = valn

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

首先要做的是foreach

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

由于某种原因,即使我已经导入了 System.Core & System.Linq 库放入项目后,我的dev-env intellisense中没有显示扩展的LINQ扩展。因此,到目前为止,除非有人可以帮助我使LINQ扩展出现在Intellisense中,否则它们就不可能了。

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.

发现了LINQ扩展没有显示出来,所以它们又回到了桌面上;)

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

推荐答案

我会用Linq编写整个方法块像这样(对不起C#-vb.net汤...)

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

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

此外,我真的不知道set是什么,也许你会必须强制转换:

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

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



vb.net:



vb.net:

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

希望这会有所帮助,

这篇关于将字典转换为结构化格式的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆