使用谓词从列表中删除元素

Ste*_*lis 8 c# collections linked-list list

我有一个.NET集合库的列表,我想删除一个元素.可悲的是,我无法通过直接与另一个对象进行比较来找到它.

我担心,使用FindIndexRemoveAt将导致列表的多个遍历.

我不知道如何使用枚举器来删除元素,否则可能会有效.

RemoveAll 做我需要的,但在找到一个元素后不会停止.

想法?

Oli*_*bes 12

List<T>有一个FindIndex接受谓词的方法

int index = words.FindIndex(s => s.StartsWith("x"));
words.RemoveAt(index);
Run Code Online (Sandbox Code Playgroud)

删除以"x"开头的第一个单词.在这个例子中words被假定为a List<string>.


Jon*_*eet 1

编辑:现在OP已更改为使用 a LinkedList<T>,很容易给出一个仅在必须迭代的范围内的答案:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)