0

したがって、IEqualityComparerを使用しようとしたのはこれが初めてであり、問​​題が発生しています。

コードが舞台裏で何をしているのか正確に理解していない可能性があります。

私が提供しているリストは次のようになります。

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

Distinct()を使用して、一意のSNを持つアイテムの数を見つけようとしていますが、「retest==1」です。

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

また、派生したIEqualityCompareクラスは次のようになります。

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;
    }
}

問題は、これが最初の2つの項目を含むを生成するように見えるのに対し、私が探しているのは、「retest==1」である単一の項目のみを含むリストであるということです。

私がここで間違っていることについて何か考えはありますか?'retest == 0'のレコードが返されるのはどうしてですか?

答え

条件がfalseの場合、オブジェクトは等しくないかのように扱われます。Distinctは等しくない行を返します。ところで、あなたはこのタイプのコードでIEqualityComparerの契約に違反しています。結果は実際には未定義です。– usr

「契約に違反している」とは、たとえば、retest==0のオブジェクトがそれ自体と等しくないことを比較することを意味します。– usr

4

1 に答える 1

1

retest = 0のアイテムを除外する必要があります。Distinctの前に.Where(x => x.retest!= 0)を配置します。

于 2012-04-25T18:41:01.173 に答える