.net IEnumerable Except that the custom IEqualityComparer does not work as expected

I am currently a bit confused about the IEnumerable.Except () method. I tried to assemble the specified operations with the data identifier of the objects. So, I wrote a custom Equality Comparer. But the result is completely not what I expected. Example:

class Program
{
    static void Main(string[] args)
    {
        List<int> IntList1 = new List<int> { 42, 43 };
        List<int> IntList2 = new List<int> { 42 };

        var intResultList = IntList1.Except(IntList2).ToList();
        intResultList.ForEach(s => Console.WriteLine(s));

        List<DataStructure> List1 = new List<DataStructure> { new DataStructure { DataID = 42, SomeText = "42" }, new DataStructure {DataID = 43, SomeText = "43"} };
        List<DataStructure> List2 = new List<DataStructure> { new DataStructure { DataID = 42, SomeText = "42" }};

        var comparer = new DataStructureComparer();

        var resultList = List1.Except(List2, comparer).ToList();

        resultList.ForEach(s => Console.WriteLine(s.SomeText));

        Console.ReadLine();
    }
}

public class DataStructureComparer: IEqualityComparer<DataStructure>
{

    public bool Equals(DataStructure x, DataStructure y)
    {
        return x.DataID == y.DataID;
    }

    public int GetHashCode(DataStructure obj)
    {
        return obj.GetHashCode();
    }
}

public class DataStructure
{
    public int DataID;
    public string SomeText;
}

The output is as follows: 43 42 43

But I would expect it to be 43 43

Why is my assumption wrong?

brgds Sven Weyberg

+4
source share
1 answer

The reason for this is your implementation GetHashCode(). It provides different hash codes for all of your instances DataStructure.

Change it to something like:

public int GetHashCode(DataStructure obj)
{
    return obj.DataID;
}

, Except - . , Equals, , .

, . object.GetHashCode(), .

DataID, -.

+7

Source: https://habr.com/ru/post/1668543/


All Articles