[英]How to iterate KeyValue List and how to read key from console and display its value on console in C#
我將一些城市名稱存儲為鍵,並將其郵政編碼存儲為KeyValuePair列表中的值,並嘗試從控制台作為用戶輸入讀取密鑰,並希望在控制台上顯示其標價。 有人可以幫我實現這一目標。
List<KeyValuePair<string, string>> City = new List<KeyValuePair<string, string>> (){
new KeyValuePair<string, string>("Ind", "1"),
new KeyValuePair<string, string>("Aus", "2"),
new KeyValuePair<string, string>("Pak","3"),
new KeyValuePair<string, string>("Eng","4"),
new KeyValuePair<string, string>("USA","5")
};
foreach (KeyValuePair<string, string> kvp in City)
{
Console.WriteLine("Enter City name or Zipcode");
var input = Console.ReadLine();
if (input == kvp.Key)
{
Console.WriteLine("Zipcode of {0} is:{1}",
input, kvp.Value);
Console.ReadLine();
}
else
{
Console.WriteLine("Zipcode of {0} is: {1}",
input, kvp.Value);
Console.ReadLine();
}
}
使用字典代替列表。 另外,while循環是一個無限循環,而不是循環列表中的項目。 嘗試:
Dictionary<string, string> City = new Dictionary<string, string>();
City.Add("Ind", "1");
City.Add("Aus", "2");
City.Add("Pak", "3");
City.Add("Eng", "4");
City.Add("USA", "5");
while (true)
{
Console.WriteLine("Enter City name. Press x to Exit");
var input = Console.ReadLine();
if (input == "x")
return;
if (!City.TryGetValue(input, out string zipCode))
Console.WriteLine("Invalid City");
Console.WriteLine("Zipcode of {0} is:{1}", input, zipCode);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.