通过VB .Net中的集合进行迭代(就像它是一个关联数组!)

时间:2012-02-08 02:51:29

标签: .net vb.net collections loops

除非我必须使用.Net,否则我不得使用.Net。我喜欢PHP的做事方式,但似乎我很难使用Collection Object来存储/检索我需要的数据。我的Collection加载了我的Objects和迭代整个集合的代码,我的问题是我无法检索“密钥”,因为它将在PHP中调用(我相信这种情况下它实际上是对象的名称)。请考虑以下示例:

            Dim xDoc As XPathDocument = New XPathDocument(fName)
            Dim xNav As XPathNavigator = xDoc.CreateNavigator()

            Dim sender As XPathNodeIterator
            sender = xNav.Select("/data/sender/val")
            While (sender.MoveNext())
                SenderInfo.Add(sender.Current.GetAttribute("n", ""), sender.Current.Value)
            End While

            For Each item As Object In SenderInfo
                Dim value As String = item.ToString()
                //need to store the key here
                Dim key As String = Nothing
            Next

如您所见,我正在浏览XML文档,并使用一些键/值对创建Object。如果它在JSON中,它将看起来像这样:

{"name":"John Smith","address1":"123 Anywhere St.","city":"This City","state":"FL"}

当我迭代Collection时我只能得到对象的值,但是我需要Key,在这个例子中我想要“name”,“address1”,“city”,“state”来存储在每次迭代的变量中。

有什么想法吗?或者我是以错误的方式解决这个问题?

在此先感谢您的帮助,我真的被这个问题困住了!

2 个答案:

答案 0 :(得分:5)

SenderInfo应为Dictionary<String,String>Here是底部的文档和示例代码,包括VB.NET。

答案 1 :(得分:3)

现在很难确定你想用这个代码做什么,而这可以在世界上为我建议做的事情做出改变。但听起来你真的想要一个这样的课程:

<Serializable()>
Public Class Sender

    Public Property Name
    Public Property Address1
    Public Property City
    Public Property State

End Class

然后用以下内容替换现有代码:

Dim xmlRdr As New Xml.Serialization.XmlSerializer(GetType(Sender))

Using fileStream As New StreamReader(fName)
     Dim mySender As Sender = xmlRdr.Deserialize(fileStream)
End Using

您可能需要在类中添加一些属性来调整反序列化程序期望xml的外观。您可以在此处阅读有关序列化的更多信息:
http://msdn.microsoft.com/en-us/library/ms950721.aspx