2012-08-27 20 views
-1

我有兩個數組,數組testAnswer包含「考試答案」,數組inputAnswers包含「學生對考試的答案」。c#爲什麼交集方法返回這個?

我想顯示正確的和不正確的答案。換句話說,試圖顯示testAnswer具有那個inputAnswers的值(不正確答案),以及兩個數組的值都有共同的值(正確答案)。

爲此,我使用了使用linq的.Except和.Intersect方法;然而我越來越奇怪的輸出:

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

你可以在'inputAnswer'上發佈測試值嗎? – Habib

回答

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 
}