Matt Abney
Matt Abney

Reputation: 17

Checking a word against a dictionary

I want a way of checking a word against a dictionary (if at all possible). If not possible against a dictionary then check against a list of words (txt or excel sheet).

Dim word As String

Console.WriteLine("Enter a message: ")
word = Console.ReadLine()

' If word <> dictionary Then
' Console.WriteLine("word in the dictionary")
' End If

Upvotes: 0

Views: 797

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460118

Do you want to know if the word is in the dictionary's key or value?

If dictionary.ContainsKey(word) Then
    Console.WriteLine("Word in Dictionary-Key")
End If
If dictionary.ContainsValue(word) Then
    Console.WriteLine("Word in Dictionary-Value")
End If

(assuming that the Dictionary(Of TKey, TValue) is a Dictionary(Of String, String))

ContainsKey is the most efficient approach. If you even want to know if it's part of a key or value you have to use a loop or Linq (which also uses loops internally):

If dictionary.Keys.Any(Function(k) k.Contains(word)) Then
    Console.WriteLine("Part of word in Dictionary-Key was word")
End If
If dictionary.Values.Any(Function(k) k.Contains(word)) Then
    Console.WriteLine("Part of word in Dictionary-Value was word")
End If

Upvotes: 2

Related Questions