LinkedList <t>(2.0):迭代删除项目</t>

时间:2009-08-17 15:44:19

标签: c# java

我需要遍历LinkedList<T>(在.NET 2.0中)并根据给定的条件删除所有项目。 这是Java下的简单方法,因为我可以执行以下操作:

Iterator<E> i = list.iterator();
while (i.hasNext()) {
    E e = i.next();
    if (e == x) {
        // Found, so move it to the front,
        i.remove();
        list.addFirst(x);
        // Return it
        return x;
    }
}

不幸的是,在IEnumerator<T>的.NET行为(相当于Iterator<E>)中,没有remove方法从集合中删除当前元素。 此外,在LinkedList<T>中无法访问给定索引处的元素,通过从最后一个迭代到第一个来完成任务。

你知道怎么做吗?非常感谢你!

4 个答案:

答案 0 :(得分:13)

这将删除符合条件的所有节点,在一个循环中通过链表。

LinkedListNode<E> node = list.First;

while (node != null)
{
    var next = node.Next;
    if (node.Value == x) {
        list.Remove(e);
    }
    node = next;
}

我相信你正在尝试...你还在列表开头的节点中添加了回来(因此你的java代码没有删除所有节点,而是将第一个匹配移到了开头列表)。使用这种方法也很容易。

答案 1 :(得分:1)

在C#中实际上要容易得多。

function PlaceAtHead(<T> x)
{
   list.Remove(x);
   list.AddFirst(x);
   return x;
}

答案 2 :(得分:1)

一个丑陋的选择是遍历您的列表,找到所有适用的项目并将它们存储在列表中。然后遍历第二个列表并在LinkedList上调用remove ...

我希望其他人有更优雅的解决方案:)

答案 3 :(得分:1)

使用谓词添加Reed Copsey's answer

    public static T MoveAheadAndReturn<T>(LinkedList<T> ll, Predicate<T> pred)
    {
        if (ll == null)
            throw new ArgumentNullException("ll");
        if (pred == null)
            throw new ArgumentNullException("pred");


        LinkedListNode<T> node = ll.First;
        T value = default(T);

        while (node != null)
        {
            value = node.Value;
            if (pred(value))
            {
                ll.Remove(node);
                ll.AddFirst(node);
                break;
            }
            node = node.Next;
        }

        return value;
    }
相关问题