Search code examples
c#arrayslinqintersectexcept

c# why is the intersect method returning this?


I have two arrays, array testAnswer holds "answers to a exam" and array inputAnswers holds "students answers to the exam".

I am trying to display the correct, and incorrect answers. In other words, trying to show what values testAnswer has that inputAnswers doesnt(incorrect answers), and also the values both arrays have in common(correct answers).

For this I have used the .Except and .Intersect method using linq; however I am getting this weird output:

B, D, A, C

Can anyone PLEASE help me, i've been at this for ages!

MY CODE:

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

Solution

  • Intersect does set intersection, so it discards duplicate values. If you want to compare answers, a better option would be to go through the arrays in parallel:

    for(int i=0; i<testAnswer.Length; i++) {
        if(testAnswer[i] == inputAnswer[i])
            listBox1.Items.Add(inputAnswer[i]); // or testAnswer[i], as appropriate
    }