1

我意识到我无法通过LinkedList.Enumerator.

例如,我尝试将以下 Java 代码移植到 C#:

Java代码:

ListIterator<Double> itr1 = linkedList1.listIterator();
ListIterator<Double> itr2 = linkedList2.listIterator();
while(itr1.hasNext() && itr2.hasNext()){
    Double d = itr1.next() + itr2.next();
    itr1.set(d);
}

C#代码:

LinkedList<Double>.Enumerator itr1 = linkedList1.GetEnumerator();            
LinkedList<Double>.Enumerator itr2 = linkedList2.GetEnumerator();

 while(itr1.MoveNext() && itr2.MoveNext()){                
    Double d = itr1.Current + itr2.Current;
    // Opps. Compilation error!
    itr1.Current = d;
}

我可以使用任何其他技术吗?

4

2 回答 2

5

C# 的LinkedList枚举器枚举的是,而不是节点

如果您想像 Java 版本一样修改节点,我认为您必须手动“枚举”节点:

LinkedListNode<Double> nod1 = linkedList1.First;
LinkedListNode<Double> nod2 = linkedList2.First;
while (nod1 != null && nod2 != null)
{
    Double d = nod1.Value + nod2.Value;              
    nod1.Value = d;
    nod1 = nod1.Next;
    nod2 = nod2.Next;
} 
于 2012-10-08T09:46:31.030 回答
0

也许只需构建一个新列表就足够了:

linkedList1 = new LinkedList<double> (linkedList1.Zip(linkedList2, (first, second) => first + second));

如果您需要更改原始列表,您可能想要做

 var tmp = linkedList1.Zip(linkedList2, (first, second) => first + second).ToList ();
 linkedList1.Clear ();
 linkedList1.AddRange (tmp);
于 2012-10-08T09:41:15.020 回答