0

I have a generic dictionary of objects and want to use a custom comparer to update the value in the dictionary.

myObjects contains a dictionary of objects and the value is the number of times that object exists. Note that the value may be incremented numerous times using different comparators or removed altogether.

testObject is my custom object.

customComparer is a dynamically changing comparer based on the type of testObject. but all comparers are of the type IEqualityComparer<MyObject>

IDictionary<MyObject, int> myObjects;
var testObject;
var customComparer;

if (myObjects.Keys.Contains(testObject, customComparer))
{
    //get the value, if its > 1 then decrement the value
    //else remove the entry entirely
    //not sure how to get the value based on my custom comparer??

    //this code below does not work because it requires the custom comparer
    //var occurrences = myObjects[testObject];
    //if (occurrences > 1)
    //    myObjects[testObject]--;
    //else
    //    myObjects.Remove(testObject);
}
else
{
    myObjects.Add(testObject, 1);
}

I can use Keys.Contains to determine if the object exists with custom comparer but then i'm not sure how to update the value?

4

2 に答える 2

4

辞書を作成するときIEqualityComparerは、コンストラクターでカスタムを提供する必要があります。ディクショナリが構築された後に等値比較子を変更することはできません。

カスタム比較子に従って一致するキーが見つかるまで、キーと値のペアを反復処理できますが、辞書が提供する機能を利用していません。

于 2011-12-05T17:27:47.053 に答える
1

これに対する迅速な実装はありませんでした。代わりに、多数の内部等値比較子を格納するラッパー IEqualityComparer を作成しました。ラッパーは、比較オブジェクトのプロパティに基づいて等値比較子の適切な内部ディクショナリを選択する Equals および GetHashCode メソッドを上書きしました。

public class WrapperComparer : IEqualityComparer<MyObject>
{
    private IDictionary<string, IEqualityComparer<MyObject>> _myComparerList;

    public bool Equals(MyObject x, MyObject y)
    {
        var comparer = _myComparerList[x.SomeProperty];
        return comparer.Equals(x, y);
    }

    public bool GetHashCode(MyObject obj)
    {
        var comparer = _myComparerList[obj.SomeProperty];
        return comparer.GetHashCode(obj);
    }
}

その後、比較が機能します...

var testObject;
var customComparer = new WrapperComparer(list of comparers here);
IDictionary<MyObject, int> myObjects = 
    new Dictionary<MyObject, int>(customComparer);

if (myObjects.ContainsKey(testObject))
{
    var occurrences = myObjects[testObject];
    if (occurrences > 1)
      myObjects[testObject]--;
    else
      myObjects.Remove(testObject);
}
else
{
    myObjects.Add(testObject, 1);
}
于 2011-12-06T13:43:50.803 に答える