mardi 16 mars 2021

Why doesn't LINQ .Distinct filter out the things that are evaluated to be equals by the same comparer?

See the following code sample (taken from a larger source)

Type plastHingeType1 = null;
Type plastHingeType2 = null;
foreach (Type type in
    (assembly.GetTypes().Concat(dynamicSerializers.Keys))
    // this distinct does not work as expected
    // note the equality comparer
    .Distinct(EqualityComparer<Type>.Default)
    )
{
    if (plastHingeType1 is null && type.Name == "PlasticHingeSettings")
    {
        plastHingeType1 = type;
    }
    else if (plastHingeType1 != null && type.Name == "PlasticHingeSettings")
    {
        plastHingeType2 = type;
    }
    // this will be true
    // even though it uses the same equality comparer that the .Distinct call used
    bool test = EqualityComparer<Type>.Default.Equals(plastHingeType1, plastHingeType2);

the problem is, that the linq .Distinct will not filter out a type, that should have been filtered out, because the specified comparer returns true to it and the previous occurence.

There is no paralell execution or anything extra around this code, what could be the problem?





Aucun commentaire:

Enregistrer un commentaire