我需要迭代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;
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,在IEnumerator<T>(相当于Iterator<E>)的.NET行为中,没有remove方法可以从集合中删除当前元素.此外,在LinkedList<T>无法访问给定索引处的元素的情况下,通过从最后一个迭代到第一个来完成任务.
你知道怎么做吗?非常感谢你!
Ree*_*sey 13
这将通过链接列表在一个循环中删除符合条件的所有节点.
LinkedListNode<E> node = list.First;
while (node != null)
{
var next = node.Next;
if (node.Value == x) {
list.Remove(e);
}
node = next;
}
Run Code Online (Sandbox Code Playgroud)
我相信你正在尝试...你还在列表开头的节点中添加了回来(因此你的java代码没有删除所有节点,而是将第一个匹配移动到列表的开头) ).这种方法也很容易做到.
| 归档时间: |
|
| 查看次数: |
4729 次 |
| 最近记录: |