I have a list from the .NET collections library and I want to remove a single element. Sadly, I cannot find it by comparing directly with another object.
I fear that using FindIndex
and RemoveAt
will cause multiple traversals of the list.
I don't know how to use Enumerators to remove elements, otherwise that could have worked.
RemoveAll
does what I need, but will not stop after one element is found.
Ideas?
List<T>
has a FindIndex
method that accepts a predicate
int index = words.FindIndex(s => s.StartsWith("x"));
words.RemoveAt(index);
Removes first word starting with "x". words
is assumed to be a List<string>
in this example.
If you want to remove only the first element that matches a predicate you can use the following (example):
List<int> list = new List<int>();
list.Remove(list.FirstOrDefault(x => x = 10));
where (x => x = 10)
is obviously your predicate for matching the objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With