-1

我有两个数组,数组 testAnswer 保存“考试答案”,数组 inputAnswers 保存“学生考试答案”。

我正在尝试显示正确和不正确的答案。换句话说,试图显示 testAnswer 有哪些值 inputAnswers 没有(不正确的答案),以及两个数组共有的值(正确的答案)。

为此,我使用了 .Except 和 .Intersect 使用 linq 的方法;但是我得到了这个奇怪的输出:

B, D, A, C

任何人都可以帮助我,我已经在这个地方很久了!

我的代码:

private void button1_Click(object sender, EventArgs e)
  {
      string[] testAnswer = new string[20] { "B", "D", "A", "A", "C", "A", "B", 
           "A", "C", "D", "B", "C", "D", "A", "D", "C", "C", "B", "D", "A" };
      string a = String.Join(", ", testAnswer);

     // Reads text file line by line. Stores in array, each line of the 
     // file is an element in the array
      string[] inputAnswer = System.IO.File
              .ReadAllLines(@"C:\Users\Momo\Desktop\UNI\Software tech\test.txt");
      string b = String.Join(", ", inputAnswer);

      var inter = inputAnswer.Intersect(testAnswer);
      foreach (var s in inter)
       {
          listBox1.Items.Add(s);
        }
     }   
4

1 回答 1

3

Intersect确实设置了交集,因此它会丢弃重复的值。如果要比较答案,更好的选择是并行遍历数组:

for(int i=0; i<testAnswer.Length; i++) {
    if(testAnswer[i] == inputAnswer[i])
        listBox1.Items.Add(inputAnswer[i]); // or testAnswer[i], as appropriate
}
于 2012-08-27T05:45:36.770 回答