使用LinkedList 的扩展

csharp
阅读 41 收藏 0 点赞 0 评论 0

LinkedListExtensions.cs
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);
    }

}
评论列表


问题


面经


文章

微信
公众号

扫码关注公众号