I'm trying to count the occurrences of every word within a text file (case insensitive) and store the words and their counts in a list.
This is my object class for the every word to be stored in the list,
public class WordItem
{
public string Word { get; set; }
public int Count { get; set; }
}
and my code function to parse the text files
public List<WordItem> FindWordCount()
{
//I've successfully parsed the text file into a list
//of words and stripped punctuation up to this point
//and stored them in List<string> wordlist.
List<string> wordlist;
List<WordEntry> entries = new List<WordEntry>();
foreach (string word in wordlist)
{
WordItem temp = new WordItem();
temp.Word = word;
temp.Count = 1;
entries.Add(temp);
}
}
How can I edit my word count function to prevent duplicates words in the list, and instead increment the count value everytime I find the word an additional time?
I would use a
Dictionary
with a case insensitive string-comparer:You can use it in this way: