admin管理员组

文章数量:1305586

I am writing a little library where I have this class:

public class ClaimPath : IEquatable<ClaimPath>
{
    public IEnumerable<ClaimIdentifier> Identifiers { get; private set; } = new List<ClaimIdentifier>();

    public bool Starred { get; private set; }

    public ClaimPath(IEnumerable<ClaimIdentifier> identifiers, bool starred)
    {
        // Irrelevant
    }

    public ClaimPath(string value)
    {
        // Irrelevant
    }    

    public override bool Equals(object obj)
    {
        return Equals(obj as ClaimPath);
    }

    public bool Equals(ClaimPath other)
    {
        if (other == null)
            return false;

        return Identifiers.SequenceEqual(other.Identifiers);
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Identifiers);
    }

    public override string ToString()
    {
        var path = string.Join("/", Identifiers.Select(v => v.Value));
        return Starred ? $"{path}/*" : path;
    }
}

public class ClaimPathComparer : IEqualityComparer<ClaimPath>
{
    public ClaimPathComparer()
    {
        var x = 0; // DEBUGGER HERE ACTIVATES
    }

    public bool Equals(ClaimPath claimPath1, ClaimPath claimPath2)
    {
        if (claimPath1 == null || claimPath2 == null)
            return false;

        return claimPath1.Equals(claimPath2);
    }

    public int GetHashCode([DisallowNull] ClaimPath obj)
    {
        return obj.GetHashCode();
    }
}

For this class I have a test to specifically verify that the Distinct method on a list containing objects of this type.

[TestMethod]
public void TheTest()
{
    var listOfClaimPaths = new List<ClaimPath>
    {
        new ClaimPath("A"),
        new ClaimPath("B"),
        new ClaimPath("C"),
        new ClaimPath("A"),
        new ClaimPath("B"),
        new ClaimPath("C")
    };

    var distinctList = listOfClaimPaths.Distinct();
    var distinctList2 = listOfClaimPaths.Distinct(new ClaimPathComparer());

    Assert.IsFalse(true);
}

EDIT: Removed issue with the Distinct debugger.

The problem appears to be the HashCode.Combine(Identifiers); not being able to correctly compute the hash, breaking the Distinct logic.

Just to clarify, I do not need the IEqualityComparer<ClaimPath>, I created it only for testing purpose.

I am writing a little library where I have this class:

public class ClaimPath : IEquatable<ClaimPath>
{
    public IEnumerable<ClaimIdentifier> Identifiers { get; private set; } = new List<ClaimIdentifier>();

    public bool Starred { get; private set; }

    public ClaimPath(IEnumerable<ClaimIdentifier> identifiers, bool starred)
    {
        // Irrelevant
    }

    public ClaimPath(string value)
    {
        // Irrelevant
    }    

    public override bool Equals(object obj)
    {
        return Equals(obj as ClaimPath);
    }

    public bool Equals(ClaimPath other)
    {
        if (other == null)
            return false;

        return Identifiers.SequenceEqual(other.Identifiers);
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Identifiers);
    }

    public override string ToString()
    {
        var path = string.Join("/", Identifiers.Select(v => v.Value));
        return Starred ? $"{path}/*" : path;
    }
}

public class ClaimPathComparer : IEqualityComparer<ClaimPath>
{
    public ClaimPathComparer()
    {
        var x = 0; // DEBUGGER HERE ACTIVATES
    }

    public bool Equals(ClaimPath claimPath1, ClaimPath claimPath2)
    {
        if (claimPath1 == null || claimPath2 == null)
            return false;

        return claimPath1.Equals(claimPath2);
    }

    public int GetHashCode([DisallowNull] ClaimPath obj)
    {
        return obj.GetHashCode();
    }
}

For this class I have a test to specifically verify that the Distinct method on a list containing objects of this type.

[TestMethod]
public void TheTest()
{
    var listOfClaimPaths = new List<ClaimPath>
    {
        new ClaimPath("A"),
        new ClaimPath("B"),
        new ClaimPath("C"),
        new ClaimPath("A"),
        new ClaimPath("B"),
        new ClaimPath("C")
    };

    var distinctList = listOfClaimPaths.Distinct();
    var distinctList2 = listOfClaimPaths.Distinct(new ClaimPathComparer());

    Assert.IsFalse(true);
}

EDIT: Removed issue with the Distinct debugger.

The problem appears to be the HashCode.Combine(Identifiers); not being able to correctly compute the hash, breaking the Distinct logic.

Just to clarify, I do not need the IEqualityComparer<ClaimPath>, I created it only for testing purpose.

Share Improve this question edited Feb 5 at 13:42 Norcino asked Feb 3 at 18:36 NorcinoNorcino 6,6276 gold badges29 silver badges49 bronze badges 5
  • 2 Your test uses Distinct, but since the method is using deferred execution, you need to do something to actually execute it, for example append Count, ToList or use a foreach. – Tim Schmelter Commented Feb 3 at 18:57
  • You can see what's going on in this fiddle dotnetfiddle/SZIJXf – Charlieface Commented Feb 3 at 18:59
  • 2 Or putting it another way: had you done something like Assert.IsFalse(distinctList.Count() == distinctList2.Count()) then it would have worked. – Charlieface Commented Feb 3 at 19:02
  • Yes thanks I got cough by the deferred execution, I didn't realise, and I was misled by the equality check I was running after. the distinct. – Norcino Commented Feb 5 at 9:24
  • 1 OK then you should fix up the title and clean up your post, because Distinct has nothing to do with this. Don't leave EDIT in your post. – Charlieface Commented Feb 5 at 12:22
Add a comment  | 

2 Answers 2

Reset to default 1

I'm not sure why you expected a random List<SomeClass> to do some funky hashcoding without you telling it to. You need to combine the hashcodes yourself, which is what the HashCode class is actually for.

The static HashCode.Combine<T>(T value1) (for a single value) doesn't do any of that, it only exists because of dynamic function resolution (resolving different numbers of parameters), as you could just as well do value1.GetHashCode() yourself.

public override int GetHashCode()
{
    var hash = new HashCode();
    foreach (var identifier in Identifiers)
        hash.Add(identifier);  // you can add a comparer here

    return hash.ToHashCode();
}

Turns out that invoking .Distinct() does not let debug any of the Equals() nor the GetHashCode(). EDIT: (Thanks for the comments) Because I was not executing the code, being deferred, I had to use any method to trigger it, such .ToList(), .Count() and so on.

In fact breakpoints are not hit even on the class where the Distinct was working.

I had to replace the implementation of the GetHashCode() override method, manually generating the hash:

public override int GetHashCode()
{
    // Any prime number 13, 17
    int hash = 13;

    foreach (var identifier in Identifiers)
    {
        hash = hash * 17 + (identifier?.GetHashCode() ?? 0);
    }

    return hash;
}

In the documentation I was unable to find any reference about to the inability to use the HashCode.Combine<T1>(T1 t) with IEnumerables parameters, but I believe that's the source of the problem.

本文标签: cDistinct not working when HashCodeCombineltgt() used with collection parametersStack Overflow