【问题标题】:Except() gives wrong output for two arrays?except() 为两个数组提供错误的输出?
【发布时间】:2012-08-21 06:17:05
【问题描述】:

我有两个数组,我需要显示 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));

【问题讨论】:

  • 您遇到了仅返回类型全名的object.ToString() 实现。你想从Except 得到什么?许多人惊讶地发现它是基于集合的 - 所以像 order 和 duplicates 这样的东西对输出没有影响。

标签: c# .net linq except


【解决方案1】:

a.Except(b) 的类型为 IEnumerable&lt;string&gt;,而 MessageBox.Show() 接受 string

所以你需要转换前两秒,例如:

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

将用逗号分隔每个元素。

【讨论】:

    【解决方案2】:

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

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

    EDIT这一行也存在同样的问题:

    string a = Convert.ToString(testAnswer);
    

    你应该用

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

    【讨论】:

    • 同样的问题也存在于例如string a = Convert.ToString(testAnswer);string.Join 也是解决这些问题的方法。 C# 中的数组没有提供非常丰富的 .ToString() 方法(这是 Convert.ToString"" + something 都使用的方法)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 2018-03-15
    • 2016-12-10
    • 2022-11-25
    • 2015-07-06
    • 1970-01-01
    相关资源
    最近更新 更多