Linq的Except方法不适用于字节值

Mon*_*tty 3 .net c# linq

    [TestMethod()]
    public void TestExceptWithRandomInput()
    {
        byte[] listA =  new byte[4096];
        var rand = new Random();
        rand.NextBytes(listA);

        byte[] listB = new byte[] { 0x00 };
        var nullCount = (from a in listA
                         where a == 0x00
                         select a);

        var listC = listA.Except(listB);

        Assert.AreEqual(4096, listA.Length);
        Assert.AreEqual(4096 - nullCount.Count(), listC.Count()); //Fails!!
    }

    [TestMethod()]
    public void TestWhereWithRandomInput()
    {
        byte[] listA = new byte[4096];
        var rand = new Random();
        rand.NextBytes(listA);

        byte[] listB = new byte[] { 0x00 };
        var nullCount = (from a in listA
                         where a == 0x00
                         select a);

        var listC = listA.Where(a => !listB.Contains(a));

        Assert.AreEqual(4096, listA.Length);
        Assert.AreEqual(4096 - nullCount.Count(), listC.Count()); //Successful
    }
Run Code Online (Sandbox Code Playgroud)

使用Except()函数时上面的代码似乎失败但在使用Where()时工作正常.似乎缺少什么?我需要为字节实现IEqualityComparer吗?我认为这只是复杂类型所必需的.

Raw*_*ing 7

Except也摆脱了第一个参数中的重复.这是一个集合操作,集合并不意味着重复 - 与之相同Union,Intersect等等.

listA.Except(listB)给出所有唯一的非空字节listA.

如果要获取序列中的所有非空字节,listA.Where(b => b != 0x00)可能是合乎逻辑的事情.

如果要计算空字节数,则listA.Count(b => b == 0x00)表达最清楚.

如果你想要一个"除了但保留重复",而不是!Contains对每个效率不高的项目进行操作,你可以做类似的事情:

public static IEnumerable<T> ExceptWithDuplicates<T>(
    this IEnumerable<T> source1,
    IEnumerable<T> source2)
{
    HashSet<T> in2 = new HashSet<T>(source2);
    foreach(T s1 in source1)
    {
        if(!in2.Contains(s1)) // rather than if Add
        {
            yield return s1;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

(免责声明:不是在IDE中编写的.)这与常规内容基本相同Except,但它不会源项添加到内部HashSet,因此它将多次返回相同的项.