繁体   English   中英

Except()为两个数组给出错误的输出?

[英]Except() gives wrong output for two arrays?

我有两个数组,我需要显示array1没有array2的内容,反之亦然。

string[] a = { "hello", "momo" }
string[] b = { "hello"}

输出:

momo

我正在使用.Except并尝试在消息框中显示输出,但是当我执行代码时,输​​出为:

System.Linq.Enumerable+<ExceptIterator>d_99'1[System.Char]

我的代码:

//Array holding answers to test
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 = Convert.ToString(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 = Convert.ToString(inputAnswer);

//Local variables
int index = 0;
Boolean arraysequal = true;

if (testAnswer.Length != inputAnswer.Length)
{
    arraysequal = false;
}

while (arraysequal && index < testAnswer.Length)
{
    if (testAnswer[index] != inputAnswer[index])
    {
        arraysequal = false;
    }
    index++;
}

MessageBox.Show("" + a.Except(b));

您应该将其转换为字符串-否则,它是可枚举的,并且ToString不会产生预期的结果。

MessageBox.Show(string.Join(", ", a.Except(b)));

编辑此行中存在相同的问题:

string a = Convert.ToString(testAnswer);

您应该将其替换为

string a = String.Join(", ", testAnswer); // << You can use a different separator

a.Except(b)具有IEnumerable<string>的类型,而MessageBox.Show()接受string

因此,您需要转换前两秒,例如:

string output = String.Join(", ", input)`

将以逗号分隔每个元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM