繁体   English   中英

在 C# 字典中使用 ToUpper 和 ToLower 来检查 ContainsKey 的用户输入

[英]User input check for ContainsKey using ToUpper and ToLower in C# Dictionary

尝试在 C# 控制台应用程序中使用ToUpperToLower验证来验证用户定义的字符串是否在包含 string 和 int 元素的 Dictionary 中,然后使用ConstainsKey打印出元素。 例如(简化):

Dictionary<string, int> example = new Dictionary<string, int>();

//int for number of each type of element
int elements = 3;

for (int i = 0; i < elements; i++)
{
     Console.WriteLine("What is the key?");
     string stringElement = Console.ReadLine();
     
     //Validation loop
     while (string.IsNullOrWhileSpace(stringElement))
     {
          Console.WriteLine("error");
          Console.WriteLine("What is the key?");
          stringElement = Console.ReadLine();
     }
     //Ask user for value
     Console.WriteLine("What is the value?");

     string numElementString = Console.ReadLine();

     while (string.IsNullOrWhiteSpace(intElementString) || (!(int.TryParse(numElementString, out numElement))) || numElement <= 0)
     {
          Console.WriteLine("error");
          Console.WriteLine("What is the value?");
          numElementString = Console.ReadLine();
     }
     example.Add(stringElement, numElement);
}

//What does user want to have printed
Console.WriteLine("What elements are you looking for? Please type in the key you need.");

//Catch key user answers
string userAnswer = Console.ReadLine();

//userAnswer validation look for IsNullOrWhiteSpace
while (string.IsNullOrWhiteSpace(userAnswer))
{
     Console.WriteLine("error");
     Console.WriteLine("What elements are you looking for? Please type in the key you need.");
     userAnswer = Console.ReadLine();

我已经做到了,我只是在使用ToUpperToLower表达式让控制台打印出用户从指定用户输入中想要的字典中的特定<string, int>变量时遇到问题。 任何朝正确方向的推动都会有所帮助......现在只想要一个简单的解决方案,因为我仍在学习编程语言。

您不需要使用ToUpperToLower来尝试以不区分大小写的方式查找密钥。 相反,您可以将比较器传递给字典的构造函数,指定它在添加或检索项目时应忽略大小写:

var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

现在,当您搜索一个值时,它会进行不区分大小写的比较以尝试找到它:

// Add a value using lower case key
dict.Add("foo", "bar");  

// Search for a value using upper case returns 'true'
if (dict.ContainsKey("FOO")) { } 

并且尝试添加具有不同大小写的键将引发带有消息“已添加具有相同键的项目”ArgumentException

dict.Add("Foo", "bar2")  // Argument exception - key already exists

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM