LinkedList 上的 LINQ - 迭代 LinkedListNode<T>,而不是 T [英] LINQ on a LinkedList - iterate over LinkedListNode&lt;T&gt;, not T

查看:23
本文介绍了LinkedList 上的 LINQ - 迭代 LinkedListNode<T>,而不是 T的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解如何在 LINQ 中执行某些操作时遇到问题.

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

我有一个链表,对象的类型无关紧要.重要的是我想根据当前对象和列表中的下一个对象之间的关系在 Where() 中做一些事情.

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))?

如果可能的话,这样做的语法是什么?类型推断系统似乎坚持我希望 lambda 参数是 T,而不是 LinkedListNode.

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;
        }
    }
}

所以你可以使用

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

这篇关于LinkedList 上的 LINQ - 迭代 LinkedListNode<T>,而不是 T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆