LINQ-集合内部的过滤器集合 [英] LINQ - filter collection inside collection
问题描述
假设我有以下课程:
class Parent
{
bool Gender { get; set; }
List<Child> Children { get; set; }
}
class Child
{
bool Gender { get; set; }
List<Child> GrandChildren { get; set; }
}
class GrandChild
{
bool Gender { get; set; }
}
使用linq,谁能帮助我通过返回List<Child>
来过滤一个Parent对象,其中每个子代都有Gender == false
,每个子代的GrandChild都有Gender == false
?
Using linq, can anyone help me filter a Parent object by returning a List<Child>
where each Child has Gender == false
and each Child's GrandChild has Gender == false
?
我设法返回了List<GrandChild>
,但是我确实需要维护层次结构.
I've managed to return a List<GrandChild>
but I really need the hierarchy to be maintained.
推荐答案
您的问题有点含糊.这是一个重建子代和子代列表的解决方案,我不确定是否需要child.GrandChildren.All(gc =>!gc.Gender),因此为了清楚起见,我省略了它:
Your question is a bit vague. Here's a solution which rebuilds the children and grandchildren lists, I wasn't sure if I needed the child.GrandChildren.All(gc => !gc.Gender) so I left it out for clarity:
parents.Select(parent => new Parent
{
Gender = parent.Gender,
Children = parent.Children.Where(child => !child.Gender).Select(child => new Child
{
Gender = false,
GrandChildren = child.GrandChildren.Where(gc => !gc.Gender).ToList()
}
).ToList()
})
这篇关于LINQ-集合内部的过滤器集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!