Skip to content

Instantly share code, notes, and snippets.

@pmunin
Last active January 12, 2016 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmunin/d8cb8b39513b33e31cae to your computer and use it in GitHub Desktop.
Save pmunin/d8cb8b39513b33e31cae to your computer and use it in GitHub Desktop.
Extension for working with LinkedList<T>
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