递归LINQ和呢? [英] Recursive linq and this?

查看:126
本文介绍了递归LINQ和呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到谁是左撇子的所有的人用递归LINQ 的通过扩展方法。

I want to find all Persons who are left handed using recursive linq via extension method.

我已经看到了这个回答但与这是一个问题(恕我直言) (如扩展方法,因为静态情况下的应用时)

I've seen this answer but there is a problem (imho) with the this : (when applied as extension method because of the static context)

关键字这不是静态方法有效

keyword this is not valid in static method

因此​​,这里是我已经试过:

So here is what i've tried :

我有一个类:

public class Person
{
        public  List<Person> Children = new List<Person>();
        public bool IsLeftHanded;
}

这里是code为externsion方式:

And here is the code for the externsion method :

public static class Extensions
{   
        public static IEnumerable<Person> DescendantsAndSelf(this IEnumerable<Person> list)
        {
         yield return this;
        foreach (var item in list.SelectMany(x => x.Children.DescendantsAndSelf()))
        {
            yield return item;
        }
    }
}

但与收益率的回报这是一个问题;

问:

我怎样才能修订我的code,以支持的我和我的孩子的的猫腻? (目标:找到谁是左手所有人)

How can I fix my code in order to support the "me and my childs" trick ? ( goal : find all persons who are left handed)

NB

请注意,我想使用LINQ和递归以获得经验与LINQ使用递归。

推荐答案

这是一个将工作在任何收集更宽泛的版本。

This is a more generic version that would work on any collection.

public static IEnumerable<T> SelectDescendents<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)
{
        foreach(var item in source)
        {
            yield return item;
            foreach(T item2 in SelectDescendents(selector(item), selector))
                yield return item2;
        }
}

用法

Persons.SelectDescendents(p => p.Children);

这篇关于递归LINQ和呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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