-1

我需要一种方法来获得用户的响应。

例如,他们键入“hat”,它会在控制台写入行中的数组表中显示价格。它还需要在二维数组而不是字典中完成

 class Table
{
    string[,] names = {
                      {"rice", "50"}, 
                      {"chip", "20"}, 
                      {"hat", "50"}, 
                      {"ball", "34"}, 
                      };
}
class Program
{
    static void Main(string[] args)
    {
        string Res;
        Console.WriteLine("What product would you like?");
        Res = Console.ReadLine();
        Console.ReadKey();
    }
}
4

3 回答 3

1

使用一种Dictionary<string, string>方式,您可以Value根据Key

Dictionary<string, string> example = new Dictionary<string, string>();
example.Add("hat", "50");
//Add the rest in this manner

你可以像这样进行查找

 if (example.ContainsKey(Res))
    string price = example[Res];
于 2013-11-11T20:28:44.160 回答
1

二维数组的简单解决方案:

class Program
{
    static void Main(string[] args)
    {
        var products = new[,] { {"rice", "50"}, {"chip", "20"}, {"hat", "50"}, {"ball", "34"} }; 

        Console.WriteLine("What product would you like?");
        var request = Console.ReadLine();

        string value = null;
        if (request != null)
        {
            for (int i = 0; i < products.GetUpperBound(0); i++)
            {
                if (products[i, 0] == request)
                {
                    value = products[i, 1];
                    break;
                }
            }
        }

        if (!string.IsNullOrEmpty(value))
        {
            Console.WriteLine("You've  selected: " + request + ". Value is: " + value);
        }
        else
        {
            Console.WriteLine("You've  selected: " + request + ". No value found.");
        }

        Console.ReadKey();
    }
}
于 2013-11-11T20:36:06.910 回答
0

您应该使用字典而不是锯齿状数组。它更好,您可以获得更大的灵活性。

var items = new Dictionary<string, string>(5); 
items.Add("rice", "50");
items.Add("chip", "20");
// and so on

然后您通过首先检查密钥是否存在来获取该项目:

if (items.ContainsKey("rice"))
{
   // it exists! read it:
   Console.WriteLine(items["rice"]);
}
于 2013-11-11T20:29:48.693 回答