C#使用SequenceEqual嵌套选择

本文关键字:选择 嵌套 SequenceEqual 使用 | 更新日期: 2023-09-27 18:22:07

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

C#使用SequenceEqual嵌套选择

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

但除此之外,您的样本数据永远不会返回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 };