[英]User input check for ContainsKey using ToUpper and ToLower in C# Dictionary
尝试在 C# 控制台应用程序中使用ToUpper
和ToLower
验证来验证用户定义的字符串是否在包含 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();
我已经做到了,我只是在使用ToUpper
和ToLower
表达式让控制台打印出用户从指定用户输入中想要的字典中的特定<string, int>
变量时遇到问题。 任何朝正确方向的推动都会有所帮助......现在只想要一个简单的解决方案,因为我仍在学习编程语言。
您不需要使用ToUpper
或ToLower
来尝试以不区分大小写的方式查找密钥。 相反,您可以将比较器传递给字典的构造函数,指定它在添加或检索项目时应忽略大小写:
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.