在对学生考试进行评分时,有两个字符阵列代表正确的问题答案/学生答案。目标是成绩并识别错过的问题并显示问题编号和正确答案答案以及学生选择。
下面的代码循环遍历两个数组并识别错过的问题。我想使用LINQ来重构现有的代码。我查看了.except,.union和.intersect运算符,但不认为它们适合于手头的任务。什么标准查询运算符可以合理地用于计算正确的结果以及此代码的外观?
System.IO.StreamReader file =
new System.IO.StreamReader(@"c:\words.txt");
while((line = file.ReadLine()) != null)
{
string[] split = line.Split('=');
string First = split[0] + " = ";
string Second = split[1];
//actually you can use split[0] and split[1], the two above llines are for demo
counter++;
}
输出
void Main()
{
char[] correctAnswer ="ACBCDABCABDDCCBA".ToCharArray();
char[] studentsChoice = "ABBCDDBCAADDACCA".ToCharArray();
for( int x = 0; x<=correctAnswer.Count()-1;x++)
{
if( ! correctAnswer[x].Equals(studentsChoice[x]))
{
Console.WriteLine(String.Format("Question:{0} correctAnswer:{1} StudentsChoice:{2}",x, correctAnswer[x],studentsChoice[x]));
}
}
答案 0 :(得分:2)
您可以为答案键添加索引,然后只需将其进行比较
string[] result = studentsChoice.Select((c,i)=> new { index = i, choice = c })
.Where(c=> c.choice != correctAnswer[c.index])
.Select(c => $"Question:{c.index+1} AnswerKey:{c.choice} Correct:{correctAnswer[c.index]}")
.ToArray();
旧版C#版本的字符串格式:
string[] result = studentsChoice.Select((c,i)=> new { index = i, choice = c })
.Where(c=> c.choice != correctAnswer[c.index])
.Select(c => string.Format("Question:{0} AnswerKey:{1} Correct:{2}",c.index+1,c.choice,correctAnswer[c.index]))
.ToArray();
请检查工作DEMO