问题描述
我有一个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
发现了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())
希望这会有所帮助,
这篇关于将字典转换为结构化格式的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!