class Program
{
static void Main(string[] args)
{
Dictionary<string, string> questionDict = new Dictionary<string, List<string>>(); //creating animal dict
List<string> removeKeys = new List<string>(); //so I can remove the keys if need be
questionDict.Add("Does it have whiskers?", "cat");
questionDict.Add("Does it purr?", "cat");
questionDict.Add("Does it bark?", "dog");
while (true)
{
foreach (KeyValuePair<string, string> kvp in questionDict)//checks for each value of kvp in questionDict
{
Console.WriteLine("Computer: {0}", kvp.Key); //prints kvp, or in this instance, the question
string userInput = Console.ReadLine();
if (userInput.ToLower() == "yes") //if yes THEN
{
Console.WriteLine("VAL: {0}", kvp.Value); //writes the value
}
else
{
removeKeys.Add(kvp.Key); //adds the wrong animals to the removeKeys list
}
}
foreach(string rKey in removeKeys)
{
questionDict.Remove(rKey); //removes all the values of rKey in removeKeys from questionDict
}
}
}
}
new Dictionary<string, List<string>>();
给了我错误。有什么帮助吗?我试图让我的字典每个键有多个值,我被告知这只能通过List<string>
来实现。
将声明更改为:
Dictionary<string, List<string>> questionDict = new Dictionary<string, List<string>>();
被赋值的变量的泛型参数必须与您正在实例化的参数匹配。当然,类型也必须匹配(它已经匹配了(。请确保对代码的其他适用部分(如foreach
循环定义(进行此更正。
请注意,如果你喜欢var(即使你不喜欢,这也是可以使用的更好的地方之一(,你可以写:
var questionDict = new Dictionary<string, List<string>>();
哪个更短,更难搞砸!