繁体   English   中英

C#Linq嵌套使用SequenceEqual选择

[英]C# Linq nested selects with SequenceEqual

我坚持使用自行编写的linq表达式-有人能够向我解释为什么这不起作用吗?

这是代码

private static void LinQSequenceEqualNested()
{
    var obj1 = new SimplyClass();
    var obj2 = new SimplyClass();
    var obj3 = new SimplyClass();
    var resultObj1 = new SimplyClass();

    obj1.ByteArray = new byte[] { 0x00, 0x01, 0x02 };
    obj2.ByteArray = new byte[] { 0x00, 0x01, 0x02 };
    obj3.ByteArray = new byte[] { 0x11, 0x11, 0x11 };
    resultObj1.ByteArray = new byte[] { 0x00, 0x01, 0x02 };

    ICollection<SimplyClass> expectedCollection = new Collection<SimplyClass>();
    expectedCollection.Add(obj1);
    expectedCollection.Add(obj2);
    expectedCollection.Add(obj3);

    ICollection<SimplyClass> resultCollection = new Collection<SimplyClass>();
    resultCollection.Add(resultObj1);
    resultCollection.Add(resultObj1);
    resultCollection.Add(resultObj1);


    if (expectedCollection.Select(expectedObj => expectedObj.ByteArray).SequenceEqual(resultCollection.Select(resultObj => resultObj.ByteArray)))
    {
        MessageBox.Show("results as expected");
    }
}

我想检查一下,在具有属性(是字节数组)的两组类中是否具有相同的序列,但它始终返回false。

最好的问候,ehmkey

Byte[]不会覆盖Equals ,因此无论如何都无法正常工作。 您可以为SequenceEqual实现自定义IEqualityComparer<SimplyClass>

public class ByteArrayComparer: IEqualityComparer<SimplyClass>
{
    public bool Equals(SimplyClass x, SimplyClass y)
    {
        if(x == null || y == null || x.ByteArray == null || y.ByteArray == null)
            return false;
        return x.ByteArray.SequenceEqual(y.ByteArray);
    }

    public int GetHashCode(SimplyClass obj)
    {
        unchecked
        {
            if (obj.ByteArray == null)
            {
                return 0;
            }
            int hash = 17;
            foreach (byte b in obj.ByteArray)
            {
                hash = hash * 31 + b;
            }
            return hash;
        }
    }
}

现在这可以工作(如果...请参见下文):

if (expectedCollection.SequenceEqual(resultCollection, new ByteArrayComparer()));
    MessageBox.Show("results as expected");  // we get here

但是除此之外,由于那些byte []明显不同,因此示例数据永远不会返回true。 使用以下示例数据,它将返回true(使用上面的代码):

obj1.ByteArray = new byte[] { 0x00, 0x01, 0x02 };
obj2.ByteArray = new byte[] { 0x00, 0x01, 0x02 };
obj3.ByteArray = new byte[] { 0x00, 0x01, 0x02 };

resultObj1.ByteArray = new byte[] { 0x00, 0x01, 0x02 };

暂无
暂无

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

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