假设我有以下课程:
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,任何人都可以通过返回每个Child List<Child>
并且每个Child的GrandChild都有Gender == false
的{{1}}来帮助我过滤父对象吗?
我设法返回Gender == false
,但我确实需要维护层次结构。
答案 0 :(得分:12)
您正在寻找
.Where(p => p.Children.All(c => !c.Gender && c.GrandChildren.All(g => !g.Gender))
答案 1 :(得分:6)
你的问题有点模糊。这是一个重建儿童和孙子名单的解决方案,我不确定我是否需要这个孩子.GrandChildren.All(gc =&gt;!gc.Gender)所以为了清楚起见我把它留了出来:
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()
})
答案 2 :(得分:3)
List<Child>
按字面翻译:
List<Child> results =
(
from c in theParent.Children
where !c.Gender
where c.GrandChildren.Any(gc => !gc.Gender)
select c
).ToList()
根据您的意见,您真正想要的是:
List<Parent> result =
(
from p in Parents
where !p.Gender
select new Parent()
{
Gender = p.Gender,
Children =
(
from c in p.Children
where !c.Gender
select new Child()
{
Gender = c.Gender,
GrandChildren =
(
from gc in c.GrandChildren
where !gc.Gender
select new GrandChild()
{
Gender = gc.Gender
}
).ToList()
}
).ToList()
}).ToList();
答案 3 :(得分:1)
var filteredParents =
from p in parents
where p.Children.All(child => !child.Gender &&
child.GrandChildren.All(grandChild => !grandChild.Gender))
select p;
此处使用All
方法可确保将作为参数传递给该方法的谓词对于给定序列中的所有元素都为真。
为每位父母提供代码检查,其中All
个孩子为(Gender = false
,并且All
为子女Gender = false
}。