【问题标题】:LINQ Compare two arrays and return the position and values that do not matchLINQ比较两个数组并返回不匹配的位置和值
【发布时间】: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();

标签: c# arrays linq


【解决方案1】:

您可以为答案键添加索引,然后简单地进行比较

    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

【讨论】:

  • 不得不使用 select 来获取索引使得这看起来,嗯,但无论如何这使用 linq 回答了 OP 的问题。您仍然需要循环打印结果:/
  • select 中的 $ 有什么作用? .Select(c => $
  • @Tinypond 嗯,它与 C# 6 中引入的String.Format() 相同,功能相同但更简单。 $"a={x}"string.Format("a={0},x); 相同
  • @Tinypond 如果您使用的是旧版本,您可以使用string.Format
  • 我编辑了我的答案并添加了string.Format 版本。请检查一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 2021-02-04
相关资源
最近更新 更多