我有一个EF DB上下文查询,它生成一个对象列表,如下所示:
public interface Parent
{
public string Name { get; set; }
public virtual ICollection<Child> Children {get; set;}
}
public interface Child
{
public string Name {get; set;}
public boolean isValid {get; set;}
}
查询本身如下所示
var list _dbContext.Parents.Include(x => x.Children).ToList();
我希望能够查询每个父级,提取具有isvalid=true
的每个子级的详细信息,然后将它们全部存储在一个列表中,但我不知道语法。
我想做的是
list.Where(x => x.Children.Where(child => child.isValid).toList()).toList();
但上面的操作只生成一个ILIST
有点不清楚你想要什么。但我想你想把所有的孩子都列在一个扁平的名单里?
因此,首先让我们加载具有有效子项的父项,然后选择许多子项(这将使列表扁平化)
var children = _dbContext.Parents
// Filter parents who don't have valid children
.Where(x => x.Children.Any(c => c.IsValid))
// Include all the children (this can be simplified not to pull all the data
// but for the POC I've included all)
.Include(x => x.Children)
// Flatten the list of children
.SelectMany(x => x.Children)
// Filter out the children which are invalid
.Where(x => x.IsValid)
.ToList();
我用这样一个表达式实现了这一点:
var list.Where(x => x.Children.Any(child => child.isValid)).toList();
在这种情况下,关键字any
非常强大