'IndexOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. What did I do wrong?
I'm trying to create a Word Occurrence Calculator that takes in a string List and returns a WordOccurrence object List. The WordOccurrence object takes in a string word and has a count attached to it. I want each WordOccurrence object in the List to have an accurate count of how many times a word is in the string List.
I have tried a lot of different approaches. Here is the one I am working with so far. However, I get an error message about the index being out of bounds when I run the program.
public static List<WordOccurrence> CalculateOccurrences(List<string> input)
{
List<WordOccurrence> occurrences = new List<WordOccurrence>();
HashSet<string> wordHash = new HashSet<string>();
int index = 0;
try
{
if (input == null)
{
throw new ArgumentNullException("Invalid input");
}
foreach (string word in input)
{
if(!wordHash.Add(word))
{
occurrences.Add(new WordOccurrence(word));
}
else
{
index = occurrences.FindIndex(i => i.Word == word);
occurrences[index].Count++;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return occurrences;
}
}
}
What is the best way to go about this? Is there a simpler method that I'm not aware of? Thanks in advance.
Solution 1:[1]
Thank you all for the comments, they helped me reach a solution that worked! I went with a foreach loop and used the Find() and Exists() method.
foreach (string word in input)
{
if (!occurrences.Exists(i => i.Word == word))
{
occurrences.Add(new WordOccurrence(word));
}
else
{
occurrences.Find(i => i.Word == word).Count++;
}
}
Thanks again everyone!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | thatOnePerson |
