首页 > 解决方案 > 使用 ReadLine 输入来控制我想在数组中使用哪个项目并获取它们的项目编号?

问题描述

假设我已经在程序中创建了 2 个数组(数组“a”和数组“b”),它们都有相同数量的项目。它们具有不同的值,但它们按数字顺序相互补充。我想要做的是,当我在数组“a”中输入一个项目的名称时,它应该给我该项目的编号,然后使用该数字来调用数组 b 中的一个项目的名称。为了举例说明我的想法,请检查以下代码:

假设数组“文件”有项目“abc”、“cde”、“fgh”和数组“目录有项目“123”、“456”、“789”

string[] file = new [] { "abc", "cde", "fgh" };
string[] directory = new [] { "123", "456", "789" };
string typed;
typed = Console.ReadLine();

if (typed == file[(name of one of the items in array "file" for example "abc")])

因为“abc”是数组“file”中的第一项,所以我需要一些命令将其更改为项目编号,在本例中为 [0]

{
    int given number = file[number of the item we entered]
    Process.Start(directory[given number]+file[the same number that has been converted]);
}

编辑:我很抱歉,但是当我问这个问题时我犯了一个小错误(我的意思是我问了正确的问题但忘记了它的一部分)我输入的部分“如果(输入==文件[(其中之一的名称)数组“文件”中的项目,例如“abc”)]) “我不知道如何使数组被用户输入的输入读取,你能帮我吗?

标签: c#arrays

解决方案


Array.IndexOf() 方法返回特定项目在数组中出现的索引。如果该项目根本没有出现在数组中,则它返回 -1。您可以使用此方法来满足您的要求,如下所示:

string typed = Console.ReadLine();
string[] file = {"abc", "cde", "fgh"};
int result = Array.IndexOf(file, typed);

//result of IndexOf will be 0 or higher if it found a matching string in the array
if (result >= 0)
{
   Console.WriteLine("Your input value " + typed + " exists in the array at index " + result.toString());
}
else
{
   Console.WriteLine("Your input did not match anything");
}

请参阅Array.IndexOf 的文档

注意只有当您的数组中的所有值都是唯一的时,这才能正常工作。


推荐阅读