LINQ比较两个数组并返回不匹配的位置和值 [英] LINQ Compare two arrays and return the position and values that do not match

查看:46
本文介绍了LINQ比较两个数组并返回不匹配的位置和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在为学生考试评分时,有两个字符阵列,分别代表正确的问题答案/学生的答案.目标是对成绩进行评分并识别出遗漏的问题,并显示问题编号并正确回答答案和学生选择.

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.

下面的代码循环遍历两个数组,并标识出遗漏的问题.我想使用LINQ重构现有代码.我已经看过.except,.union和.intersect运算符,但认为它们不适合当前的任务.哪些标准查询运算符可合理地用于计算正确结果,并且此代码将是什么样?

The code below loops through two arrays and identifies the missed questions. I would like to use LINQ to refactor the existing code. I have looked at the .except, .union and .intersect operators but don't feel they are the right fit for the task at hand. 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]));
        }
}

输出

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

使用较旧的C#版本的字符串格式:

String formatting with older C# versions:

    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

这篇关于LINQ比较两个数组并返回不匹配的位置和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆