1

I realize there are no way for me to replace value through LinkedList.Enumerator.

For instance, I try to port the below Java code to C#:

Java code:

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# code:

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;
}

Any other techniques I can use?

2 Answers 2

5

C#'s LinkedList enumerator enumerates the values, not the nodes.

If you want to modify nodes as in the Java version, I think you have to "enumerate" the nodes manually:

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;
} 
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe it's sufficient to simply build a new list:

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

If you need the original list to be changed, you might want to do

 var tmp = linkedList1.Zip(linkedList2, (first, second) => first + second).ToList ();
 linkedList1.Clear ();
 linkedList1.AddRange (tmp);

3 Comments

linkedList1 is a LinkedList<double> so you can't use .ToList(); You need something like: linkedList1 = new LinkedList<double>(linkedList1.Zip(linkedList2, (first, second) => first + second));
Why shouldn't I be able to use ToList () for a List<double>???? I just tried it, and I do not see any problem. It does what it is supposed to do.
Because it's not a List<>, it's a LinkedList<>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.