LINQ上链表 - 遍历一个LinkedListNode< T&GT ;,不是T遍历、链表、不是、LINQ

2023-09-03 02:41:55 作者:只偏袒你

我有一个问题,了解如何做一下LINQ。

I'm having a problem understanding how to do something in LINQ.

我有一个链表,该对象的类型并不重要。真正重要的是,我想要做的事在其中()根据当前对象的和下一个在列表之间的关系。

I have a linkedlist, the type of the object doesn't matter. What does matter is that I want to do something in a Where() based on the relationship between the current object and the next one in the list.

为什么我不能做这样的事情:

Why can't I do something like:

linkedlist.Where(N => a_function(n.Value,n.Next.Value))?

什么是语法要做到这一点,如果它甚至可能吗?该类型推理系统似乎坚持我想要的拉姆达参数是 T ,不是一个LinkedListNode< T>

What is the syntax to do this, if it's even possible? The type inference system seems to insist that I want the lambda argument to be T, not LinkedListNode<T>.

推荐答案

您将必须编写新的迭代器的链表来做到这一点。类似于

You'll have to write new iterator for linked list to do that. Something like

public static class LinkedListExtensions
{
    public static IEnumerable<LinkedListNode<T>> EnumerateNodes<T>(this LinkedList<T> list)
    {
        var node = list.First;
        while(node != null)
        {
            yield return node;
            node = node.Next;
        }
    }
}

这样你就可以使用

so you can use

linkedlist.EnumerateNodes().Where(n=>a_function(n.Value, n.Next.Value))