3
Vote

MultiDictionary Remove and RemoveMany bug

description

If you try to remove an item from a MultiDictionary when it doesn't exist and there is only one element in the MultiDictionary, the last element is removed. See code snippet below:
 
 
MultiDictionary<string, int> lMultiDictionary = new MultiDictionary<string, int>(false);
lMultiDictionary.Add("key", 1);
lMultiDictionary.Remove("key", 2);
 
If this code is executed the MultiDictionary will no longer contain any values for "key".
 
From the PowerCollections source code in MultiDictionary::Remove(TKey key, TValue value)
{
...
    if (existingCount == 1) {                                           //***** There is no check here for indexFound >= 0********
                // Removing the last value. Remove the key.
                hash.Delete(existing, out keyValues);
                return true;
            }
            else if (indexFound >= 0) {
                // Found a value. Remove it.
                if (indexFound < existingCount - 1)
                    Array.Copy(existing.Values, indexFound + 1, existing.Values, indexFound, existingCount - indexFound - 1);
                existing.Count = existingCount - 1;
 
                // Update the hash.
                hash.Find(existing, true, out keyValues);
                return true;
            }
            else {
                // Value was not found.
                return false;
            }
...
}

comments