我有两个数组,数组testAnswer保存"考试答案",数组inputAnswers保存"学生考试答案"。
我正在尝试显示正确和不正确的答案。换句话说,试图显示testAnswer有哪些值inputAnswers没有(错误答案),以及两个数组的共同值(正确答案)。
为此,我使用了。除了和。使用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:UsersMomoDesktopUNISoftware techtest.txt");
string b = String.Join(", ", inputAnswer);
var inter = inputAnswer.Intersect(testAnswer);
foreach (var s in inter)
{
listBox1.Items.Add(s);
}
}
Intersect
确实设置了交集,因此它会丢弃重复的值。如果你想比较答案,一个更好的选择是并行遍历数组:
for(int i=0; i<testAnswer.Length; i++) {
if(testAnswer[i] == inputAnswer[i])
listBox1.Items.Add(inputAnswer[i]); // or testAnswer[i], as appropriate
}