提问者:小点点

使用C#Dictionary中的ToUpper和ToLower检查ContainsKey的用户输入


尝试在C#控制台应用程序中使用ToUpToDown验证用户定义的字符串是否在字典中,其中包含字符串和int元素,然后用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();

到目前为止,我只是在使用ToUpTolower表达式让控制台打印出特定的时遇到了问题


共1个答案

匿名用户

您不需要使用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")) { } 

尝试用不同的大小写添加一个键会抛出一个ArgumentExc0019,消息是“已经添加了具有相同键的项”

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