Question

So this is the first time I've tried using IEqualityComparer and I'm running into an issue.

It's likely I just don't understand exactly what the code is doing behind the scenes.

The list I'm providing it looks like this:

Test Run | SN    | Retest
1          185     0
2          185     1
3          185     1
4          185     1

I'm trying to use Distinct() to find the number of items which have a unique SN, and 'retest==1'.

var result = testRunList.Distinct(new UniqueRetests());

And the derived IEqualityCompare class looks like this:

public class UniqueRetests : IEqualityComparer<TestRunRecord>
{
    // Records are equal if their SNs and retest are equal.
    public bool Equals(TestRunRecord x, TestRunRecord y)
    {
        //Check whether any of the compared objects is null.
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        //Check whether it's a retest AND if the specified records' properties are equal.
        return x.retest == 1 && y.retest == 1 && x.boardSN == y.boardSN;
    }

    // If Equals() returns true for a pair of objects 
    // then GetHashCode() must return the same value for these objects.

    public int GetHashCode(TestRunRecord record)
    {
        //Check whether the object is null
        if (Object.ReferenceEquals(record, null)) return 0;

        //Get hash code for the board SN field.
        int hashRecordSN = record.boardSN.GetHashCode();

        //Get hash code for the retest field.
        int hashRecordRetest = record.retest.GetHashCode();

        //Calculate the hash code for the product.
        return hashRecordSN ^ hashRecordRetest;
    }
}

Problem is that this seems to produce a which includes the first two items, whereas what I'm looking for is a list that includes only a single item where 'retest==1'.

Any idea what I'm doing wrong here? How is it that a record with 'retest == 0' is being returned?

Answer

If the condition is false, the objects are treated as if they are not equal. Distinct returns not-equal rows. Btw, you are violating the contract of IEqualityComparer with this type of code. The results are actually undefined. – usr

With "violating the contract" I mean (for example) than an object with retest==0 will compare unequal to itself. – usr

Was it helpful?

Solution

You need to filter out items with retest = 0. Put a .Where(x => x.retest != 0) in front of the Distinct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top