Last active
January 12, 2016 03:49
-
-
Save pmunin/d8cb8b39513b33e31cae to your computer and use it in GitHub Desktop.
Extension for working with LinkedList<T>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
/// <summary> | |
/// Extensions for LinkedList, allowing to enumerate nodes. | |
/// Latest version is here: https://gist.github.com/pmunin/d8cb8b39513b33e31cae | |
/// </summary> | |
public static class LinkedListExtensions | |
{ | |
/// <summary> | |
/// Enumerates previous nodes starting from current | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="node"></param> | |
/// <param name="includingCurrent">should current node be included in resultset</param> | |
/// <returns></returns> | |
public static IEnumerable<LinkedListNode<T>> PreviousAll<T>(this LinkedListNode<T> node, bool includingCurrent = false) | |
{ | |
if (includingCurrent) | |
yield return node; | |
while (node.Previous != null) | |
yield return node.Previous; | |
} | |
/// <summary> | |
/// Enumerate all nodes following next to current | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="node"></param> | |
/// <param name="includingCurrent">should current node be included in resultset</param> | |
/// <returns></returns> | |
public static IEnumerable<LinkedListNode<T>> NextAll<T>(this LinkedListNode<T> node, bool includingCurrent = false) | |
{ | |
if (includingCurrent) | |
yield return node; | |
while (node.Next != null) | |
yield return node.Next; | |
} | |
/// <summary> | |
/// Move appropriate implementation of Reverse method for LinkedList | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="list"></param> | |
/// <returns></returns> | |
public static IEnumerable<T> Reverse<T>(this LinkedList<T> list) | |
{ | |
return list.Last.PreviousAll(true).Select(l => l.Value); | |
} | |
/// <summary> | |
/// Enumerates all nodes of linked list | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="list"></param> | |
/// <returns></returns> | |
public static IEnumerable<LinkedListNode<T>> Nodes<T>(this LinkedList<T> list) | |
{ | |
return list.First.NextAll(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment