【问题标题】:How to loop trough dictionary and check if the ReadLine input is equal to the Dictionary Key如何遍历字典并检查 ReadLine 输入是否等于字典键
【发布时间】:2020-04-01 23:32:15
【问题描述】:
int userInput = Convert.ToInt32(Console.ReadLine());
            foreach (KeyValuePair<int,Library> lib in dictionary)
            {
                if (userInput == lib.Key)
                {
                    Console.WriteLine("You chose book = {0}",lib.Value.bookName);
                }
                else
                {
                    Console.WriteLine("Wrong Input");
                }
            }

您好,我一直在弄清楚如何在通过字典循环时检查用户输入(ReadLine)与字典中的键的相等性,而不会发送垃圾邮件“错误输入”的其他命令。

【问题讨论】:

标签: c# loops dictionary


【解决方案1】:

尝试使用布尔值进行验证

int userInput = Convert.ToInt32(Console.ReadLine());
bool exists= false;
            foreach (KeyValuePair<int,Library> lib in dictionary)
            {
                if (userInput == lib.Key)
                {
                    Console.WriteLine("You chose book = {0}",lib.Value.bookName);
                    exists = true;
                }
            }
            if(!exists){
                  Console.WriteLine("Wrong Input");
            }

【讨论】:

    【解决方案2】:

    目前您的代码基本上是在说“对于字典中的每个键不等于用户输入的键然后打印错误的输入..”这显然不是您想要的。

    相反,您想要以下内容:

    "遍历整个字典,如果每个键都不等于用户输入的那个,则打印错误的输入..."

    为了达到这个目的:

    1. 循环中不需要else 块。
    2. 使用一个简单的布尔变量,它会告诉您在迭代过程中是否找到匹配项,然后在循环之后检查布尔值的状态,然后在必要时打印“错误输入”。

    例子:

    bool wrongInput = true;
    int userInput = Convert.ToInt32(Console.ReadLine());
    foreach (KeyValuePair<int,Library> lib in dictionary)
    {
         if (userInput == lib.Key)
         {
               Console.WriteLine($"You chose book = {lib.Value.bookName}");
               wrongInput = false;
               break; // exit early as there's no need to continue the iterating.
         }
    }
    
    if (wrongInput) Console.WriteLine("Wrong Input");
    

    请注意,为了完整性,我已经更正了您的代码,但我不建议遵循上述方法,即遍历字典,而是查看 ContainsKey 而不是遍历字典....因为它是惯用的,较少代码,更具可读性等...

    【讨论】:

    • “最终,查看 ContainsKey 而不是遍历字典......”似乎我们在想同样的事情 ;-)
    • @zilleplus 看起来确实如此。
    • 感谢您的宝贵时间,这些都是很好的答案,但我很感兴趣如何在使用 ContainsKey 显示 bookName 的同时循环遍历字典
    【解决方案3】:

    好像.Net lib中有一个方法ContainsKey。

    https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.containskey?view=netframework-4.8

    您可以简单地调用它并删除整个循环。

    【讨论】:

      【解决方案4】:

      您可以为此使用 LinQ 并缩短代码,使其简单易读。将花费更多时间尝试验证来自用户的输入,并确保估算值是一个数字而不是其他任何东西。

       int userInput = Convert.ToInt32(Console.ReadLine());
          var result = dictionary.FirstOrDefault(x => x.Key == userInput);
          if(result.Value != null)
              Console.WriteLine("You chose book = {0}", result.Value);
          else
              Console.WriteLine("Wrong Input");
      

      另一种方法是在执行获取值之前运行布尔表达式来验证键是否存在。

              int userInput = Convert.ToInt32(Console.ReadLine());
              var result = dictionary.ContainsKey(userInput);
      
              if(!result)
                  Console.WriteLine("Wrong Input");
              else
              {
                  var book = dictionary.FirstOrDefault(x => x.Key == userInput);
                  Console.WriteLine("You chose book = {0}", book.Value);
              }
      

      【讨论】:

      • result 将是 null,而不仅仅是 result.Value,因此这可能会导致 Null Ref 异常:)
      • 我在发布之前运行了代码,没有抛出 Null Ref 异常。创建一个值为 null 的对象。
      • 但我同意这是解决问题的一种冒险方法。
      • Dictionary&lt;TKey,TValue&gt;KeyValuePair&lt;TKey,TValue&gt; 的集合,它是一个结构体,所以默认永远不会是null。但是,是的,ContainsKey 方式要好得多。如果你也想要这个价值,TryGetValue 会更好。
      • 我刚刚测试并完全同意 Corak 和 Matt 的观点,即 TryGetValue 是一种很好的方法,代码变得非常苗条。
      【解决方案5】:

      类似于 Nasar 的 Linq 实现,您可以在字典 (Docs) 上使用 TryGetValue 方法。

      使用TryGetValue 的好处是您只需对字典进行一次迭代即可完成两件事。

      1. 检查值是否存在
      2. 从字典中获取值
      int userInput = Convert.ToInt32(Console.ReadLine());
      
      if (dictionary.TryGetValue(userInput, out Library library))
          Console.WriteLine($"You chose book = {library.bookName}");
      else
          Console.WriteLine("Wrong Input");
      

      TryGetValue如果找到记录则返回true,否则返回false。

      【讨论】:

      • 感谢您的回答
      猜你喜欢
      • 2017-04-13
      • 2018-02-03
      • 2015-09-27
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多