So why isn’t there a Pop() method for lists. Look for it, finds it, removes it all at once. Instead, we have a .Contains() to make sure it’s there. Then we have a First<>() to get it. Then we have a Remove() that redoes the linear search.
Here is performance of .Remove() vs .RemoveAt(), running several loops to get an aggregate result. The numbers should be considered as relative performance to each other, since I assume no one cares about sub-millisecond execution times.
Removing by index… | 360 ms |
Removing by value… | 3218 ms |
Find by value, then remove… | 3328 ms |
And I’m not the first person to think of this.
static public T PopFirst
(this List list, Predicate test) where T:class {
var index = list.FindIndex(test);
if (index < 0)
return null;
T value = list[index];
list.RemoveAt(index);
return value;
}
Though I don't use .PopFirst()
a lot, the idea is used whereever I implement a .Contains()
in a key/value pair search.