0

今日、私は ConcurrentDictionary と Dictionary でいくつかのテストを行っていました:

class MyTest
{
    public int Row { get; private set; }
    public int Col { get; private set; }
    public string Value { get; private set; }

    public MyTest(int row, int col, string value)
    {
        this.Col = col;
        this.Row = row;
        this.Value = value;
    }


    public override bool Equals(object obj)
    {
        MyTest other = obj as MyTest;
        return base.Equals(other);

    }

    public override int GetHashCode()
    {
        return (Col.GetHashCode() ^ Row.GetHashCode() ^ Value.GetHashCode());
    }

}

上記のエンティティを使用して、ConcurrentDictionary と Dictionary を作成して入力し、以下のコードを試しました。

    ConcurrentDictionary<MyTest, List<MyTest>> _test = new ConcurrentDictionary<MyTest, List<MyTest>>();
    Dictionary<MyTest, List<MyTest>> _test2 = new Dictionary<MyTest, List<MyTest>>();

        MyTest dunno = _test.Values.AsParallel().Select(x => x.Find(a => a.Col == 1 && a.Row == 1)).FirstOrDefault();
        MyTest dunno2 = _test2.Values.AsParallel().Select(x => x.Find(a => a.Col == 1 && a.Row == 1)).FirstOrDefault();

最初のものは値を返しますが、2番目のものはそうではありません。何が間違っていますか?

これは、値を追加するために使用されるコードです。

            _test.AddOrUpdate(cell10,
            new List<MyTest>
            {
                new MyTest(1, 1, "ovpSOMEVALUEValue"),
                new MyTest(1, 2, "ocpSOMEVALUEValue")
            },
            (key, value) => value = new List<MyTest>());

        _test2.Add(cell10,
            new List<MyTest>
            {
                new MyTest(1, 1, "ovpSOMEVALUEValue"),
                new MyTest(1, 2, "ocpSOMEVALUEValue")
            }
            );
4

1 に答える 1

3

を呼び出しAddOrUpdateており、3 番目のパラメーターは新しい空のリストを作成する必要があるため、結果として空のリストが作成されます。このコード行の前のどこかに、同じキーを持つエントリを追加していると推測しています。

Equals関数が正しくないことにも注意してください。で使用する実際の値ではなく、参照で比較していますGetHashCode。Equals をオーバーライドするには、デフォルトのテンプレートを使用することをお勧めします。

     protected bool Equals(x other) {
        return Row == other.Row && Col == other.Col && string.Equals(Value, other.Value);
     }

     public override bool Equals(object obj)
     {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((x) obj);
     }

     public override int GetHashCode()
     {
        unchecked
        {
           var hashCode = Row;
           hashCode = (hashCode*397) ^ Col;
           hashCode = (hashCode*397) ^ (Value != null ? Value.GetHashCode() : 0);
           return hashCode;
        }
     }
于 2016-10-07T03:22:05.077 に答える