首页 > 解决方案 > 将正确的分数排序为正确的名称(并行数组)C#

问题描述

如上所述,我正在尝试使用并行数组向正确的用户显示正确的分数,如果学生的分数低于 40,它应该显示学生的姓名和分数。

目前我已经这样做了,但它没有将分数分配给正确的名称。

代码:

  static void Main(string[] args)
    {
        //bool YesNo = Console.ReadKey;
        // Empty Variable arrays declared for usage.
        int[] classScores = new int[5];
        string[] studentNames = new string[5];
        object[] ClassANDStudent = new object[5];

        //
        //   if (YesNo == true)
        //Loop Method for user input for student name.
        for (int i = 0; i < studentNames.Length; i++)
        {
            Console.WriteLine("Please enter a Student Name.");
            studentNames[i] = Console.ReadLine();

            Console.WriteLine("Please enter marks.");
            classScores[i] = Convert.ToInt32(Console.ReadLine());

        }
        //


        var Lessthan40Array = classScores.Where(OverallMark => OverallMark <= 40).ToArray();

        Array.Sort(studentNames, classScores, 0, studentNames.Length);
        Array.Sort(studentNames, Lessthan40Array, 0, Lessthan40Array.Length);

        for (int i = 0; i < studentNames.Length; i++)
        {
            ClassANDStudent[i] = studentNames[i] + " " + classScores[i];
        }



        //
       for (int i = 0; i < Lessthan40Array.Length; i++)
        {

            Console.WriteLine(studentNames[i] + " " + Lessthan40Array[i]);
          //  Console.WriteLine(" {0,-10}: {1}", studentNames[i], Lessthan40Array[i]);
        }

        Console.ReadKey();
    }

标签: c#arrayssorting

解决方案


如果你想在写分数之前实际排序:

static void Main(string[] args)
{
    int[] classScores = new int[]{30,50,25,39,62};
    string[] studentNames = new string[]{"Jim","John","Mary","Peter","Sarah"};
        Array.Sort(classScores, studentNames);   // sort both according to scores
    for (int i = 0; i < classScores.Length; i++)
    {
        if (classScores[i] < 40)
        {
            Console.WriteLine(classScores[i] + " " + studentNames[i]);
        }
    }
}

如果您有 2 个以上的数组,请创建一个索引为 0 到 length-1 的数组:

static void Main(string[] args)
{
    int[] classScores = new int[]{30,50,25,39,62};
    string[] firstNames = new string[]{"Jim","John","Mary","Peter","Sarah"};
    string[] lastNames = new string[]{"Thorpe","Smith","Jones","Tork","Conner"};
    int[] index = new int[]{0,1,2,3,4};
        Array.Sort(classScores, index);   // sort both according to scores
    for (int i = 0; i < classScores.Length; i++)
    {
        if (classScores[i] < 40)
        {
            Console.WriteLine(classScores[i] + " " +
                firstNames[index[i]] + " " + lastNames[index[i]]);
        }
    }
}

推荐阅读