从两个数组中获取两个值

时间:2015-12-17 15:48:27

标签: c# arrays parallel-processing

如何从并行数组输出相应的值。 (即如果我要在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 个答案:

答案 0 :(得分:1)

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]);
}

答案 1 :(得分:1)

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

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"]);
相关问题