views:

43

answers:

2

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

+3  A: 

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
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
@serhio: See my edit.
Jon Skeet
what is Tuple, is it a .NET 2, or a custom class?
serhio
@serhio: It's a class in .NET 4, but you could write your own class to represent these if you want.
Jon Skeet
+1  A: 

There is some info on how to build circular lists in C# here.

Steve Townsend
"using the simple List<T> class to store your contacts"... cool solution.
serhio
@serhio - there are other answers than the accepted one in that list
Steve Townsend