简体   繁体   中英

C# Linq nested selects with SequenceEqual

i'm sticking on a self written linq expression - is somebody able to explain me why this doesnt work?

Here is the code

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");
    }
}

I want to check, if in two sets of classes with an attribute (which is a byte array) have the same sequence, but it returns always false.

Best regards, ehmkey

Byte[] does not override Equals , so this does not work anyway. You could implement a custom IEqualityComparer<SimplyClass> for 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;
        }
    }
}

Now this would work (if... see below):

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

But apart from that your sample data would never return true because those byte[] are clearly different. It would return true (with my code above) with this sample data:

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 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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