在字典中检查密钥 - 数据减少

ConstainsKey 方法是了解字典中是否已存在密钥的方法。

这对于减少数据非常有用。在下面的示例中,每次我们添加一个新单词时,我们将其作为字典中的键添加,否则我们会增加该特定单词的计数器。

 Dim dic As IDictionary(Of String, Integer) = New Dictionary(Of String, Integer)

 Dim words As String() = Split(<big text source>," ", -1, CompareMethod.Binary)

 For Each str As String In words
     If dic.ContainsKey(str) Then
         dic(str) += 1
     Else
         dic.Add(str, 1)
     End If
 Next

XML 简化示例:在 XML 文档的分支中获取所有子节点名称和出现

Dim nodes As IDictionary(Of String, Integer) = New Dictionary(Of String, Integer)
Dim xmlsrc = New XmlDocument()
xmlsrc.LoadXml(<any text stream source>)

For Each xn As XmlNode In xmlsrc.FirstChild.ChildNodes 'selects the proper parent
    If nodes.ContainsKey(xn.Name) Then
        nodes(xn.Name) += 1
    Else
        nodes.Add(xn.Name, 1)
    End If
Next