从2个数组中获取这两个值

本文关键字:两个 2个 数组 获取 | 更新日期: 2023-09-27 18:27:08

如何从并行数组中输出相应的值。(即,如果我要在c#控制台上搜索"John",相应的数字应该显示为"34"。然而,只有John这个名字。我需要能够获得相应的数字。有什么想法吗?

        string[] sName = new string [] { "John", "Mary", "Keith", "Graham", "Susan" };
        int[] iMarks = new int [] { 34, 62, 71, 29, 50 };
        int iNumber = 0;
        string sSearch;
        for (iNumber = 0; iNumber < iMarks.Length; iNumber++)
        {
   Console.WriteLine("Number." + (iNumber + 1) + sName[iNumber] + " = " + iMarks[iNumber]);
        }
        Console.WriteLine(" Now can you enter a name to get the marks of the student");
        sSearch = Console.ReadLine();
        while (iNumber < iMarks.Length && sSearch != sName[iNumber])
        {
            iNumber++;              
        }
        if (sName.Contains(sSearch))
        {
            Console.WriteLine(sSearch + " Has been found " + iNumber );
            Console.WriteLine();
        }
        else
        {
            Console.WriteLine(sSearch + " not found, please try again");
        }

从2个数组中获取这两个值

IndexOf方法将帮助您:
string[] sName = new string [] { "John", "Mary", "Keith", "Graham", "Susan" };
int[] iMarks = new int [] { 34, 62, 71, 29, 50 };
string sSearch;
//...
int iNumber = Array.IndexOf(sName, sSearch);
if (iNumber >=0)
{
    Console.WriteLine(sSearch + " Has been found " + iMarks[iNumber]);
}

在这种情况下,我会使用一个字典而不是两个数组,因为它已经完成了值的"配对"。

Dictionary<string, int> marksDictionary = new Dictionary<string, int>();
// Just initialize the dictionary instead of the arrays
marksDictionary.Add("John", 34);
marksDictionary.Add("Mary", 62);
marksDictionary.Add("Keith", 71);
// To get the value, simply read off the dictionary passing in the lookup key
Console.WriteLine("Marks for John is " + marksDictionary["John"]);