C# “使用字典做对”;“命令”;
下面的代码示例。所以我想执行if语句。我如何通过迭代字典来实现它?“停止”和“结束”应具有相同的含义,其值为2C# “使用字典做对”;“命令”;,c#,dictionary,C#,Dictionary,下面的代码示例。所以我想执行if语句。我如何通过迭代字典来实现它?“停止”和“结束”应具有相同的含义,其值为2 Dictionary<string, int> commands = new Dictionary<string, int>() { {"start", 1}, {"stop", 2}, {"end", 2} }; string input = Console.ReadLine(); if (input.Equals(STOP or E
Dictionary<string, int> commands = new Dictionary<string, int>()
{
{"start", 1},
{"stop", 2},
{"end", 2}
};
string input = Console.ReadLine();
if (input.Equals(STOP or END))
{
//Do this
}
Dictionary命令=新建Dictionary()
{
{“开始”,1},
{“停止”,2},
{“结束”,2}
};
字符串输入=Console.ReadLine();
if(输入等于(停止或结束))
{
//这样做
}
这是您迭代字典并检查命令的方式
Dictionary<string, int> commands = new Dictionary<string, int>()
{
{"start", 1},
{"stop", 2},
{"end", 2}
};
foreach (var key in commands.Keys)
{
string input = Console.ReadLine();
if (key == "start" || key == "stop")
{
Console.WriteLine("Do what you have to do here");
}
}
Dictionary命令=新建Dictionary()
{
{“开始”,1},
{“停止”,2},
{“结束”,2}
};
foreach(命令中的var键。键)
{
字符串输入=Console.ReadLine();
如果(键==“开始”| |键==“停止”)
{
WriteLine(“在这里做你必须做的事”);
}
}
您可以使用foreach
在字典上迭代。
但根据我对你的问题的理解,我认为以下方法可行:
Dictionary<string, int> commands = new Dictionary<string, int>()
{{"start", 1}, {"stop", 2}, {"end", 2}};
string input = Console.ReadLine();
if (commands.ContainsKey((input.ToLower()))) // this checks if the input is equal to any of the keys present in the Dictionary
{
if (input.ToLower() == "end" || input.ToLower() == "stop")
{
// do this
// you can also get the value from Dictionary by key here
}
}
Dictionary命令=新建Dictionary()
{{“开始”,1},{“停止”,2},{“结束”,2};
字符串输入=Console.ReadLine();
if(commands.ContainsKey((input.ToLower()))//检查输入是否等于字典中的任何键
{
if(input.ToLower()=“end”| input.ToLower()=“stop”)
{
//这样做
//您还可以在此处通过键从字典中获取值
}
}
到目前为止您尝试了什么?在密钥集合上使用for循环或foreach循环。它可以被显式提取。例如commands.TryGetValue(),您不清楚要做什么。我唯一能帮助您的是将input.Equals(STOP或END)
更改为input==STOP | | input==END
。如果(commands.ContainsKey(input.ToInvariantLower())可能是您的开始?