【发布时间】:2018-01-27 07:06:03
【问题描述】:
在为学生考试评分时,有两个字符数组代表正确的问题答案/学生答案。目标是评分和识别错过的问题,并显示问题编号和正确答案答案和学生选择。
下面的代码循环遍历两个数组并识别错过的问题。我想使用 LINQ 重构现有代码。我看过 .except、.union 和 .intersect 运算符,但觉得它们不适合手头的任务。使用哪些标准查询运算符来计算正确的结果是合理的,这段代码会是什么样子?
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]));
}
}
输出
Question:1 AnswerKey:C Correct:B
Question:5 AnswerKey:A Correct:D
Question:9 AnswerKey:B Correct:A
Question:12 AnswerKey:C Correct:A
Question:14 AnswerKey:B Correct:C
【问题讨论】:
-
在这种情况下,我想不出 linq 能比这种方法做得更好,因为你有并行数组。
-
两个
char[]的大小总是一样吗? (意思是学生肯定回答了所有问题)。另外,如果您想要 linq,请显示一些 linq 尝试。 -
您只是想要一个更优雅的解决方案吗?你真的不能再提高效率了。
-
是的,如果(studentsChoice.Length == correctAnswer.Length)
-
顺便说一句,linq 代码也可以使用字符串
string correctAnswer ="ACBCDABCABDDCCBA";并且您不需要字符数组char[] correctAnswer ="ACBCDABCABDDCCBA".ToCharArray();