C # <T> List Contains Test

Is such if-testing required when deleting an item?

if (_items.Contains(item))
{
    _items.Remove(item);
}

And what about this test?

if (!_items.Contains(item))
{
    _items.Add(item);
}
+5
source share
2 answers

You do not need to test to remove. Remove () will return false if nothing is removed.

If you do not want to duplicate items in your list, you can check them before adding. Otherwise, you will have duplicates.

See also: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

+11
source

You can also use HashSet <T> if you want to be able to add () an item several times and only have it in the collection once, without checking Contains () first.

+7
source

All Articles