Add IndexOf extension method for LinkedListNode<T>
authorMichael Welch <michaelgwelch@gmail.com>
Tue, 21 Feb 2012 21:02:02 +0000 (15:02 -0600)
committerMichael Welch <michaelgwelch@gmail.com>
Tue, 21 Feb 2012 21:02:02 +0000 (15:02 -0600)
src.net/BrainmessCore/LinkedListNode.cs

index d9b9094..3e8811d 100644 (file)
@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using System.Diagnostics;
 
 namespace Welch.Brainmess
 {
@@ -32,6 +33,25 @@ namespace Welch.Brainmess
             return node.Previous ?? node.List.AddFirst(default(T));
             
         }
+
+        public static int IndexOf<T>(this LinkedListNode<T> node)
+        {
+            if (node == null) throw new ArgumentNullException("node");
+            if (node.List == null) throw new ArgumentException("The specified node is not linked into a list", "node");
+
+            int index = 0;
+            var current = node.List.First;
+            
+            while(current != node)
+            {
+                Debug.Assert(current != null); // Unless there is an issue in .NET LinkedListNode this can never happen. This is to turn Resharper Warning off.
+                current = current.Next;
+                index++;
+            }
+
+            return index;
+
+        }
     }
 }