C# LinkedList<;T>;(2.0):以迭代方式删除项
我需要遍历C# LinkedList<;T>;(2.0):以迭代方式删除项,c#,java,C#,Java,我需要遍历LinkedList(在.NET2.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.ad
LinkedList
(在.NET2.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;
}
}
Iterator i=list.Iterator();
while(i.hasNext()){
E=i.next();
如果(e==x){
//找到了,把它移到前面,
i、 删除();
列表。首先添加(x);
//还它
返回x;
}
}
不幸的是,在IEnumerator
(相当于Iterator
)的.NET行为中,没有remove
方法从集合中删除当前元素。
此外,在LinkedList
中,无法访问给定索引处的元素,无法通过从最后一个返回到第一个来完成任务
你知道怎么做吗?多谢各位 用C#实际上要容易得多
函数放置头(x)
{
列表。删除(x);
列表。首先添加(x);
返回x;
}
一个难看的选项是遍历列表,找到所有适用的项目并将其存储在列表中。然后遍历第二个列表并在LinkedList上调用remove
我希望其他人有一个更优雅的解决方案:)这将在链接列表的一个循环中删除所有符合条件的节点
LinkedListNode<E> node = list.First;
while (node != null)
{
var next = node.Next;
if (node.Value == x) {
list.Remove(e);
}
node = next;
}
LinkedListNode=list.First;
while(节点!=null)
{
var next=node.next;
if(node.Value==x){
删除(e);
}
节点=下一个;
}
我相信这就是你想要的。。。您还将其添加回列表开头的节点中(因此您的java代码没有删除所有节点,而是将第一个匹配项移到了列表的开头)。使用这种方法也很容易做到这一点。只需添加一个谓词:
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;
}
public static T moveaheaddredreturn(LinkedList ll,Predicate pred)
{
如果(ll==null)
抛出新的ArgumentNullException(“ll”);
if(pred==null)
抛出新的ArgumentNullException(“pred”);
LinkedListNode节点=ll.First;
T值=默认值(T);
while(节点!=null)
{
value=node.value;
if(pred(value))
{
ll.移除(节点);
ll.AddFirst(节点);
打破
}
node=node.Next;
}
返回值;
}
我还没有尝试过,但我相信这会引发一个异常,因为开放枚举器……这正是Antonello代码片段所做的。在枚举项时无法删除该项,但是.Net允许您只删除项,而无需枚举即可找到它们。从.Net任何类型的列表中删除项的标准解决方案是建立第二个删除项列表,并在枚举器完成后将其删除,这只是简化了这一点。+1适用于OP的示例,否则,如果您找到要首先删除的项,则会起作用。这也是我的想法,但是,除此之外,它不可能在每种情况下都工作,因为列表中的两个节点可能是相等的……我在下面列出了一个一次性版本,它也可以处理重复的节点。它基于使用LinkedList.Remove(LinkedListNode)为什么这是一个社区wiki?这不是一件主观的事情-这里有一个明确的答案。它不应该是列表。删除(节点)?
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;
}