简体   繁体   English

LINQ比较两个数组并返回不匹配的位置和值

[英]LINQ Compare two arrays and return the position and values that do not match

In grading student exams there are two arrays of characters which represent correct questions answers / student answers. 在对学生考试进行评分时,有两个字符阵列,分别代表正确的问题答案/学生的答案。 The goal is grade and identify the missed questions and to display the question number and correct answer answer and student choice. 目标是对成绩进行评分并识别出遗漏的问题,并显示问题编号并正确回答答案和学生选择。

The code below loops through two arrays and identifies the missed questions. 下面的代码遍历两个数组,并标识出遗漏的问题。 I would like to use LINQ to refactor the existing code. 我想使用LINQ重构现有代码。 I have looked at the .except, .union and .intersect operators but don't feel they are the right fit for the task at hand. 我已经看过.except,.union和.intersect运算符,但认为它们不适合当前的任务。 What standard query operators are reasonable to use to calculate the correct results and what would this code look like? 哪些标准查询运算符可以合理地用于计算正确的结果,这些代码将是什么样?

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

Output 输出量

    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

You can add indexing to your answer keys and then simply compare it 您可以将索引添加到答案键,然后将其进行比较

    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();

String formatting with older C# versions: 较旧的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(); 

please check the working DEMO 请检查正常的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM