Does c#/.net x.x have an implementation of a doubly linked list (that can be iterated over backwards)?

The following code will efficiently iterate over a LinkedList in reverse:

        LinkedList<string> list = new LinkedList<string>
            (new[] {"cat", "dog", "frog", "antelope", "gazelle"});
        LinkedListNode<string> item = list.Last;
        do
        {
            Console.WriteLine(item.Value);
            item = item.Previous;
        }
        while (item != null);
        Console.ReadKey();

The key here is that a LinkedList contains reference to only the First and Last LinkedListNode instances of the list. Each LinkedListNode instance holds a reference to the next and previous item in the list (or null at each end of the list) and also a Value property. This means iteration from the first or last LinkedListNode is easy, but random access requires iteration from the first or last in the list.

If you need to make an insertion along the way, use LinkedList.AddBefore or AddAfter to insert a new LinkedListNode.


As well as the answers given here, you can write an extension method to LinkedList<T> to make it slightly easier to reuse:

public static IEnumerable<T> Backwards<T>(this LinkedList<T> list)
{
    LinkedListNode<T> node= list.Last;
    while (node != null)
    {
        yield return node.Value;
        node = node.Previous;
    }
}

Use with:

foreach (string x in list.Backwards())
{
    // ...
}

How about System.Collections.Generic.LinkedList()

Here are the docs on MSDN:

http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx

Version Info
.NET Framework: Supported in: 3.5, 3.0, 2.0
.NET Compact Framework: Supported in: 3.5, 2.0
XNA Framework: Supported in: 3.0, 2.0, 1.0

That said, I am with the others that it is generally preferrable to use a higher abstraction when working with such a rich framework.