作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我已经研究了很长时间了。
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
。
最佳答案
首先我不明白为什么你所有的属性private
和 Age
不是 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
没问题,然后它会检查下一级层次结构,直到 Childrens
是null
.
所以你可以这样使用它:
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/
我是一名优秀的程序员,十分优秀!