Removing an item from a list using a predicate

I have a list from the .NET collection library and I want to delete one item. Unfortunately, I can not find it, comparing directly with another object.

I am afraid that using FindIndex and RemoveAt will lead to several crawls of the list.

I don't know how to use Enumerators to remove items, otherwise this might work.

RemoveAll does what I need, but does not stop after one element is detected.

Ideas?

+6
source share
3 answers

EDIT: now the OP has changed to use LinkedList<T> , it is easy to give an answer that only iterates as much as possible:

 public static void RemoveFirst<T>(LinkedList<T> list, Predicate<T> predicate) { var node = list.First; while (node != null) { if (predicate(node.Value)) { list.Remove(node); return; } node = node.Next; } } 
+1
source

List<T> has a FindIndex method that takes a predicate

 int index = words.FindIndex(s => s.StartsWith("x")); words.RemoveAt(index); 

Deletes the first word starting with "x". words is considered in this example List<string> .

+10
source

If you want to remove only the first element that matches the 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 objects.

+2
source

Source: https://habr.com/ru/post/906952/


All Articles