Recursive linq and this?

2019-07-21 07:51发布

问题:

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 :

I have a Person class :

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

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

But there is a problem with yield return this;

Question :

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

please notice that I want to use linq and recursion in order to get experienced with linq using recursion.

回答1:

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

Usage

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


回答2:

I'd rather see it working like this:

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

and run it against person not children, like this:

var person = new Person();
... do stuff
var desc = person.DescendantsAndSelf();

Correct me if I see it wrong.



标签: c# linq .net-4.0