我有一个通用的对象字典,并希望使用自定义比较器来更新字典中的值。
myObjects
包含对象字典,值是对象存在的次数。请注意,该值可能会使用不同的比较器多次递增或完全删除。
testObject
是我的自定义对象。
customComparer
是一个基于 testObject 类型动态变化的比较器。但所有比较器都是类型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);
}
我可以使用 Keys.Contains 来确定对象是否存在自定义比较器,但是我不确定如何更新值?