c# - 递归 linq 和这个?

标签 c# linq .net-4.0

我想通过扩展方法使用递归 linq 来查找所有左撇子。

我见过这个answer但是 this 有一个问题(恕我直言):(由于静态上下文而用作扩展方法时)

keyword this is not valid in static method

所以这是我尝试过的:

我有一个Person类:

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

这是扩展方法的代码:

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

但是yield return this;有问题

问题:

如何修复我的代码以支持“我和我的 child ”技巧? (目标:找到所有左撇子)

注意

请注意,我想使用 linq 和递归,以便获得使用递归的 linq 经验。

最佳答案

我宁愿看到它像这样工作:

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

并针对人而不是 child 运行它,如下所示:

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

如果我看错了,请纠正我。

关于c# - 递归 linq 和这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21086502/

相关文章:

c# - 在 Windows 8 桌面应用程序上使用 MediaCapture

c# - 有条件地加入 LINQ

asp.net - 将 ASP.NET 项目移动到 .NET 4

.net-4.0 - app.config "forced"(?) on .net 4.0 .. 需要吗?

javascript - 网页无法正确加载: '"JSON"is undefined' error

c# - 在当前上下文中不存在 c#

c# - system.data.sqlite 的内存数据库包装器

c# - select 子句表达式问题

linq - 在 IEnumerable 上尝试 FirstOrDefault 时抛出 TargetInvocableException

c# - LINQ to XML 和 DataGridView