-1

Bellow is my vb code, I am trying to loop through all the words inputted and place all of the unique words into a dictionary with their position. I get this error though and I don't know how to fix it. Please, can I have any suggestions; thanks.

The error:Object reference not set to an instance of an object.

Public Class Form1
    Dim sentence() As String
    Dim uniqueWords As Dictionary(Of String, Integer)

    Private Sub creatSaveBtn_Click(sender As Object, e As EventArgs) Handles creatSaveBtn.Click
        sentence = sentenceInputTxt.Text.ToLower.Split(" ")

        For Each word In sentence
            If Not uniqueWords.ContainsKey(word) Then
                uniqueWords.Add(word, uniqueWords.Count + 1)
            End If
        Next
    End Sub
End Class
Zev Spitz
  • 10,414
  • 4
  • 49
  • 114
  • If all you want is a distinct list of words, consider using a [HashSet(Of String)](https://msdn.microsoft.com/en-us/library/bb359438%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396). You call the [Add](https://msdn.microsoft.com/en-us/library/bb353005(v=vs.110).aspx) method on each potential string, and the HashSet will only add it if it's not already in the HashSet. – Zev Spitz May 23 '16 at 17:29

1 Answers1

2
Dim uniqueWords As New Dictionary(Of String, Integer)

also you could:

Dim uniqueWords As List(Of String) = sentenceInputTxt.Text.ToLower.Split(" "c).Distinct().ToList()
shadow
  • 1,840
  • 1
  • 14
  • 24