Code inspection: Dictionary item removal can be simplified with single 'Remove'
The Remove
method in Dictionary<T, T>
in C# does not throw an exception if the key is not found, it simply returns false
. This means you do not need to use TryGetValue
to check if the key exists in the dictionary before trying to remove it.
int RemoveValue(Dictionary<int, int> d, int toRemove)
{
if (d.TryGetValue(toRemove, out var result))
{
d.Remove(toRemove);
return result;
}
return -1;
}
int RemoveValue(Dictionary<int, int> d, int toRemove)
{
if (d.Remove(toRemove, out var result))
{
return result;
}
return -1;
}
Last modified: 23 July 2024