C#Linq使用SequenceEqual嵌套选择

时间:2014-09-17 11:58:37

标签: c# linq

我坚持使用自编的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

1 个答案:

答案 0 :(得分:2)

Byte[]不会覆盖Equals,因此无论如何这都不起作用。您可以为IEqualityComparer<SimplyClass>实施自定义SequenceEqual

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

但除此之外,您的样本数据永远不会返回true,因为那些byte []明显不同。它将使用此示例数据返回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 };