具有多个键的字典无法按预期工作

时间:2013-05-25 20:18:33

标签: c# list dictionary foreach

我正在制作一个控制台程序,我将多个值映射到dictionary keyLookup。我正在使用if命令使用该键输出一些console.writeline = ("stuff");但它只有在我的值和键相同(在字典中)时才有效。我不知道为什么会这样。我一直在讨论listforeach以及一些变量试图找出我做错了什么,但即使它继续工作现在如何工作它仍然不起作用我怎么样想。

此外,如果我的console.readline();中有一个单词不在我的字典中,那么整个事情就会崩溃。这是我不想要的,而且我不确定为什么它会这样做,或者在某些方面它没有。另外,我的mathFunction字典也适用于我希望keyLookup字典的工作方式。虽然我认为区别在于我如何通过keyLookup使用列表进行交叉引用。

class MainClass
    {
        public static string Line;
        static string foundKey;
        public static void Main (string[] args)
        {
            while (true) 
            {
                if (Line == null)
                {Console.WriteLine ("Enter Input"); }
                WordChecker ();
            }
    }
    public static void WordChecker()
    {
        string inputString = Console.ReadLine ();
        inputString = inputString.ToLower();  

        string[] stripChars = { ";", ",", ".", "-", "_", "^", "(", ")", "[", "]",
            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "\n", "\t", "\r" };

        foreach (string character in stripChars)
        {
            inputString = inputString.Replace(character, "");
        }
        // Split on spaces into a List of strings
        List<string> wordList = inputString.Split(' ').ToList();
        // Define and remove stopwords
        string[] stopwords = new string[] { "and", "the", "she", "for", "this", "you", "but" };

        foreach (string word in stopwords)
        {
            // While there's still an instance of a stopword in the wordList, remove it.
            // If we don't use a while loop on this each call to Remove simply removes a single
            // instance of the stopword from our wordList, and we can't call Replace on the
            // entire string (as opposed to the individual words in the string) as it's
            // too indiscriminate (i.e. removing 'and' will turn words like 'bandage' into 'bdage'!)
            while ( wordList.Contains(word) )
            {
                wordList.Remove(word);
            }
        }
        // Create a new Dictionary object
        Dictionary<string, int> dictionary = new Dictionary<string, int>();

        // Loop over all over the words in our wordList...

        foreach (string word in wordList)
        {
            // If the length of the word is at least three letters...

            if (word.Length >= 3) 
            {

                // ...check if the dictionary already has the word.

                if ( dictionary.ContainsKey(word) )
                {

                    // If we already have the word in the dictionary, increment the count of how many times it appears

                    dictionary[word]++;
                }
                else
                {
                    // Otherwise, if it's a new word then add it to the dictionary with an initial count of 1

                    dictionary[word] = 1;
                }
            }

            List<string> dicList = new List<string>();
            dicList = dictionary.Keys.ToList ();

            Dictionary<string, string> keyLookup = new Dictionary<string, string>();

            keyLookup["hey"] = "greeting";
            keyLookup["hi"] = "greeting";
            keyLookup["greeting"] = "greeting";
            keyLookup["math"] = "math";
            keyLookup["calculate"] = "math";
            keyLookup["equation"] = "math";

            foundKey = keyLookup[word];

            List<string> keyList = new List<string>();

            foreach (string keyWord in dicList)
            {
                if(keyWord == foundKey)
                {keyList.Add (keyWord); }
            }

            foreach (string mKey in keyList)
            {
            if(mKey == "greeting")
            {Greetings ();}

            if (mKey == "math") 
            {Math ();}
            }
        }
    }

    public static void Math()
    {
        Console.WriteLine ("What do you want me to math?");
        Console.WriteLine ("input a number");
        string input = Console.ReadLine ();

        decimal a = Convert.ToDecimal (input);
        Console.WriteLine("Tell me math function");
        string mFunction = Console.ReadLine();

        Console.WriteLine ("tell me another number");
        string inputB = Console.ReadLine();
        decimal b = Convert.ToDecimal (inputB);

        Dictionary<string, string> mathFunction = new Dictionary<string, string>();

        mathFunction["multiply"] = "multiply";
        mathFunction["times"] = "multiply";
        mathFunction["x"] = "multiply";
        mathFunction["*"] = "multiply";
        mathFunction["divide"] = "divide";
        mathFunction["/"] = "divide";
        mathFunction["subtract"] = "subtract";
        mathFunction["minus"] = "subtract";
        mathFunction["-"] = "subtract";
        mathFunction["add"] = "add";
        mathFunction["+"] = "add";
        mathFunction["plus"] = "add";

        string foundKey = mathFunction[mFunction];

        if (foundKey == "add")
        {
            Console.WriteLine (a + b);
        }
        else if (foundKey == "subtract")
        {
            Console.WriteLine (a - b);
        }
        else if (foundKey == "multiply")
        {
            Console.WriteLine (a * b);
        }
        else if (foundKey == "divide")
        {
            Console.WriteLine (a / b);
        }
        else
        {
            Console.WriteLine ("not a math");
        }
    }

    public static void Greetings()
    {
        Console.WriteLine("You said hello");
    }
}'

2 个答案:

答案 0 :(得分:1)

你应该以不同的方式遍历字典(不要使用ToList-Function)。

请改为尝试:

foreach (KeyValuePair kvp (Of String, String) In testDictionary)
{
  Debug.WriteLine("Key:" + kvp.Key + " Value:" + kvp.Value);
}

如果单词不匹配,你的应用程序就会崩溃,因为这个代码(你不是那样创建一个新的条目):

// Otherwise, if it's a new word then add it to the dictionary with an initial count of 1
dictionary[word] = 1;

编辑:我错了dictionary[word] = 1不会创建新元素。这样就好了。

答案 1 :(得分:0)

  

foundKey = keyLookup[word];

如果keyLookup中不存在word,那么它将崩溃。

  

string foundKey = mathFunction[mFunction];

如果mathFunction中不存在mFunction则会崩溃。


如果你想把它变成一个“对话式”程序,那么单词查找最重要的部分。您不使用谓词或LINQ,两者都可以使字符串函数极其变得容易。目前你使用字典。为什么不为每个关键字使用列表?

List<string> GreetingKeywords;
GreetingKeywords.Add("hello"); // ...

List<string> MathKeywords;
MathKeywords.Add("math"); // ...

foreach (var word in dicList)
{
  if (GreetingKeywords.Contains(word))
    { Greetings(); }
  if (MathKeywords.Contains(word))
    { Maths(); }
}

我建议你阅读谓词和List / Dictionary函数,比如Find,IndexOf等等。这些知识对于C#来说非常宝贵。