微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决用户输入在C#词典中使用ToUpper和ToLower检查ContainsKey

尝试在C#控制台应用程序中使用toupperToLower验证来验证用户定义的字符串是否在包含字符串和int元素的Dictionary中,并用{{1 }}之后。例如(简体):

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(); toupper表达式让控制台打印出字典中特定的ToLower变量只是一个问题。用户想要从指定的用户输入。朝着正确方向的任何推动都会有所帮助……由于我仍在学习编程语言,因此暂时只需要一个简单的解决方案即可。

解决方法

您无需使用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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。