hash table ? RRS feed

  • Question

  • Hi, I am a newcomer to .net and C# specifically. I developed this small program which reads a text file and prints to console a list all words contained within the text file and the amount of occurrences of each word.

    I played around a lot with the hash table/foreach section of my code and now I am confused on how hash table works. my question is in this line "foreach (string word in words)" how does the "string word" know what each word contained within the text file is? I understand  "String[] words;" line contains an array that has all the individual words that make up the text file.   maybe this is a case of over thinking a process .    

    Thanks for any help advance! 

    I pasted my code below

    using System;
    using System.Collections.Generic;
    using System.Collections;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;

    namespace ConsoleApplication2
        class Program
            static void Main()
                string txt = System.IO.File.ReadAllText(@"C:\\textfile.txt");

                Hashtable htWords = new Hashtable();
                String[] words;

                words = txt.Split(); //txt is the string from the text file
                foreach (string word in words)
                    if (htWords.Contains(word))
                        htWords[word] = (int)htWords[word] + 1;

                        htWords.Add(word, 1);

                foreach (string key in htWords.Keys)
                    Console.WriteLine(String.Format("{0}: {1}", key, htWords[key]));
    Wednesday, January 22, 2014 4:41 AM


All replies