Removing an entry
An entry sometimes has to go. A shop stops selling an item, or a player leaves the game. In a Dictionary<TKey, TValue>, you call Remove with the key, and the key and its value disappear together.
Dictionary<string, int> animals = new Dictionary<string, int>();
animals["cat"] = 4;
animals["rabbit"] = 1;
animals.Remove("rabbit");
Console.WriteLine(animals.Count);
Console.WriteLine(animals.ContainsKey("rabbit"));
1
False
Count drops by one, and ContainsKey("rabbit") now returns false. In a file of your own, add using System; and using System.Collections.Generic;.
What Remove returns
Remove returns a bool. It is true when it found the key and deleted it, and false when the key was not there. In the second case nothing changes and nothing throws, so removing a key that is already gone is safe. Calling animals.Remove("rabbit") a second time returns false, and Count stays the same.
There is also a form that hands back the removed value: animals.Remove("cat", out int count) returns true and sets count to 4.
Watch out: after the delete, reading animals["rabbit"] throws a KeyNotFoundException, because the key is gone. Check with ContainsKey first, or read with a default.
Removing several entries, and clearing all
To delete every entry that meets a rule, loop over a copy of the keys, such as animals.Keys.ToList() (with using System.Linq;), and call Remove inside the loop. For example, removing every animal with a count under 3 from the pet shop's dictionary leaves only the cats. To empty the whole dictionary, call Clear(), and Count becomes 0.
The returned bool can also drive an if: if (animals.Remove("rabbit")) { ... } runs its body only when a rabbit entry really existed and was deleted.
The exercise, step by step
A pet shop counts what it has for sale: 4 cats, 2 dogs and 1 rabbit. The last rabbit has just gone home with a family.
- Delete the key. Under the first
Console.WriteLine, callanimals.Remove("rabbit"). The key and its count of 1 both go. - Print the count again.
animals.Countis now 2, one less than before.
The code that was already there checks for rabbits. With the key gone, ContainsKey("rabbit") is false, so the else branch runs.
Dictionary<string, int> animals = new Dictionary<string, int>();
animals["cat"] = 4;
animals["dog"] = 2;
animals["rabbit"] = 1;
Console.WriteLine(animals.Count);
animals.Remove("rabbit");
Console.WriteLine(animals.Count);
if (animals.ContainsKey("rabbit")) {
Console.WriteLine("We still have rabbits");
} else {
Console.WriteLine("No rabbits left");
}
3
2
No rabbits left
Details and traps
- Count of animals versus Count of keys.
animals.Countis the number of keys, 3 at the start. It is not the total number of animals, which would be 7. - Setting a value to 0 is not deleting.
animals["rabbit"] = 0;keeps the key, soCountstays 3 andContainsKey("rabbit")is still true. UseRemoveto delete. - Exact keys.
Remove("Rabbit")does nothing when the key is"rabbit". It returnsfalse. - Remove takes a key, not an index. A dictionary has no positions, and there is no
RemoveAt. - Ignoring the result is usual. You can call
Removeas a statement. Use the returnedboolonly when you need to know whether something was deleted.
Key takeaways
d.Remove(key)deletes the key and its value.- It returns
truewhen it deleted something, andfalsewhen the key was missing. - A missing key is not an error for
Remove, but reading it afterwards withd[key]is. Countgoes down by one after a successful removal.
