1

I have a question about LinkedList<>.
There are properties of this list First and Last.

Will that properties correct if I will set Last.AddNext(First)?

I need to have a list where Last>Next = First, but identify clearly the First and Last elements.

I have a cycle process.NextStep, NextStep, but need to be able to identify each Step (process[i] - the i-th Step)

.NET 2

serhio
  • 28,010
  • 62
  • 221
  • 374
  • You mean you're trying to build a circular list? I doubt you can do that with the default class. I would expect `Last.AddNext(First)` to append a copy of the first element to the end of the list but not create a loop. – Rup Oct 08 '10 at 13:20

1 Answers1

3

LinkedList<T> doesn't support circular lists. From the docs:

The LinkedList<T> class does not support chaining, splitting, cycles, or other features that can leave the list in an inconsistent state.

There's no such method as LinkedListNode<T>.AddNext(), but I'd expect any attempt to cause a cycle to fail with an exception.

You could always build an iterator based on a LinkedList<T> though...

(Note that this will fail if the list is empty...)

public static IEnumerable<Tuple<T, bool, bool>> IterateInCycles<T>
    (LinkedList<T> source)
{
    LinkedList<T> node = source.First;
    while (true)
    {
        yield return Tuple.Create(node.Value,
                                  node.Previous == null,
                                  node.Next == null);
        node = node.Next ?? source.First;
    }
}

Each tuple in the return sequence will be (value, isFirst, isLast) if you see what I mean.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • e... what should this mean, or... can I replace it by something... I think this is a common problem and there should be a common solution... – serhio Oct 08 '10 at 13:28
  • what is Tuple, is it a .NET 2, or a custom class? – serhio Oct 08 '10 at 13:34
  • @serhio: It's a class in .NET 4, but you could write your own class to represent these if you want. – Jon Skeet Oct 08 '10 at 13:43