Does C # /. NET xx implement a doubly linked list (which can be repeated in reverse order)?

I was looking for a standard implementation of a doubly linked list in C # (so that I have a linked list that I can iterate over) and cannot find it. I feel that something so simple should have an implementation that I just miss.

If it exists, for which version of C # /. Net does it exist?

The reverse iteration generally seems to be something not meant for C #. Is my brain stuck too much in C ++ / stl mode or is it something really missing in C #?

I know LinkedList, but, unable to find a way to iterate over it back, suggested that it was connected separately.

If LinkedList has a double binding, how can I repeat it backwards (efficiently)?

+6
collections linked-list c # iteration
source share
4 answers

Like the answers given here, you can write an extension method for LinkedList<T> to make it somewhat easier to reuse:

 public static IEnumerable<T> Backwards(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()) { // ... } 
+6
source share

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

  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 LinkedList only contains reference to instances of the First and Last LinkedListNode of the list. Each instance of LinkedListNode contains a link to the next and previous element in the list (or null at each end of the list), as well as the Value property. This means that iterating from the first or last LinkedListNode is simple, but random access requires iterating from the first or last in the list.

If you need to make input in a path, use LinkedList.AddBefore or AddAfter to insert a new LinkedListNode.

+10
source share

How about System.Collections.Generic.LinkedList ()

Here are the docs on MSDN:

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

Version Information
.NET Framework: Supported in: 3.5, 3.0, 2.0
.NET Compact Framework: Supported in: 3.5, 2.0
XNA Framework: supported in versions: 3.0, 2.0, 1.0

However, I am with others that it is usually better to use a higher abstraction when working with such a rich structure.

+2
source share

What about LinkedList ?

+1
source share

All Articles