gpt4 book ai didi

c# - LINQ 获取所有继承人的 child

转载 作者:太空狗 更新时间:2023-10-30 00:39:29 25 4
gpt4 key购买 nike

我已经研究了很长时间了。

public class Person
{
public string Name { get; set; }
public string Age { get; set; }
public List<Person> Children { get; set; }
}

我想要一个 LINQ 查询来找出“此集合中所有 Age > 4 的人”。

注意:你必须遍历 Person Collection + Children Collection,所以每个子对象都有一个 Person 集合,直到 Children 变为 null

最佳答案

首先我不明白为什么你所有的属性privateAge不是 int类型。所以我的课看起来像这样:

public partial class Person
{
public string Name { get; set; }
public int Age { get; set; }
public List<Person> Childrens { get; set; }
}

备注partial单词。这个词将允许您将类逻辑放在单独的文件中,这在您在类中创建一些自定义逻辑时可能很有用。

然后我简单地在不同的文件中创建这个方法:

public partial class Person
{
public Person GetPersonWithChindren(int maxAge)
{
return new Person
{
Age = this.Age,
Name = this.Name,
Childrens = this.Childrens != null
? this.Childrens
.Where(x => x.Age < maxAge)
.Select(x => x.GetPersonWithChindren(maxAge)) //this line do recursive magic
.ToList()
: null
};
}
}

如您所见,此方法检查 Age每个 child ,如果Age没问题,然后它会检查下一级层次结构,直到 Childrensnull .

所以你可以这样使用它:

var person = new Person()
{
//initialisation of your collection here
}

//result will contains only nodes where Person have age < 4 and Childs that have age < 4
var result = person.GetPersonWithChindren(4);

请注意,此解决方案将与 linqToEntities 一起正常工作。但是,如果您使用 LinqToSQL,此表达式会在每个 Person 上生成对 DB 的查询。实体。所以如果你有很多人和很深的层次结构,它会花费你很多机器时间。在这种情况下,您应该使用 CTE 而不是 LinQ 查询来编写存储过程。

更新:

您甚至可以借助 Func<T> 编写更通用的解决方案像这样上课:

public partial class Person
{
public Person GetPersonWithChindren(Func<Person, bool> func)
{
return new Person
{
Age = this.Age,
Name = this.Name,
Childrens = this.Childrens != null
? this.Childrens
.Where(x => func(x))
.Select(x => x.GetPersonWithChindren(func))
.ToList()
: null
};
}
}

然后你可以像这样使用它:

var result = person.GetPersonWithChindren(x => x.Age < 4);

您现在随时可以在要使用您的功能的地方更改您的条件。

关于c# - LINQ 获取所有继承人的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35123780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com