簡體   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