c# - 将正确的分数排序为正确的名称(并行数组)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();
}
解决方案
如果你想在写分数之前实际排序:
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]]);
}
}
}
推荐阅读
- java - 从数据库下载文件:找不到类 java.io.ByteArrayInputStream 的序列化程序,也没有发现创建 BeanSerializer 的属性
- python - 使用 df.at[] += x 增加 DataFrame 的单元格值不起作用
- mysql - 如何在mysql之上的spark中查询字符串时间
- c - 从另一个文件中未定义的对“功能”的引用
- java - 如何使用 Lombok 生成只接受部分参数的构造函数?
- reactjs - 如何调试 WordPress React 插件?
- gdb - 从 spi 配置返回时,Arty-A7-100T 上 E310 上的 example-spi 卡住了
- javascript - Google Apps 脚本 Oauth1 / Trello API“无效签名”
- bazel - Jenkins(Linux,CentOS)上的 Bazel 本地 JDK 权限问题
- swiftui - ForEach 循环中单元格的屏幕截图