Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should List<T>.Remove be preceded with List<T>.Exists?

Tags:

Having List<string> paths = new List<string>(); I want to remove item that I'm not sure is there. Should I check if it exists or just run the Remove method straight ahead?

Is if (paths.Exists(stringVar)) needed or considered a good practice before paths.Remove(stringVar)?

Running Remove without Exists would simply return false in case there is no such item in list.

like image 326
yosh Avatar asked May 30 '11 10:05

yosh


People also ask

What method do you use to remove an item from a list t at a specific index?

RemoveAt (Int32) Method is used to remove the element at the specified index of the List<T>. Properties of List: It is different from the arrays.

How does list Remove Work C#?

The Remove method removes the first occurrence of a specific object from a List. The Remove method takes an item as its parameter. We can use the RemoveAt method to remove an item at the specified position within a List. The Remove method removes the first occurrence of a specific object from a List.

How do you remove an element from a generic list while iterating over it?

The best way to remove items from a list while iterating over it is to use RemoveAll() .


2 Answers

No it doesn't throw an exception, and there is no need for extra checking . see MSDN:

true if item is successfully removed; otherwise, false. This method also returns false if item was not found in the List.

like image 99
Saeed Amiri Avatar answered Sep 28 '22 10:09

Saeed Amiri


No, don't check. Because Remove already does the check. Your extra check is simply superfluous and brings no benefit.

like image 30
Daniel Hilgarth Avatar answered Sep 28 '22 10:09

Daniel Hilgarth