Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing element from list with predicate

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?

like image 934
Steinbitglis Avatar asked Jan 26 '12 16:01

Steinbitglis


2 Answers

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.

like image 65
Olivier Jacot-Descombes Avatar answered Sep 28 '22 08:09

Olivier Jacot-Descombes


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.

like image 22
Strillo Avatar answered Sep 28 '22 09:09

Strillo