我理解你的问题,你想返回所有Items
无论如何,但你想过滤SubItems
。对于IQueryable
,没有好方法说“我想要返回此对象,但我想要修改版本的X属性”。如果你想这样,你将不得不使用select语句来选择一个新对象。
选项1:返回单独的数据
var itemsAndSubItems = items
.Select(item => new
{
Item = item,
SubItems = item.SubItems.Where(sub => sub.ID = 1)
}
);
,或者如果你不介意的热切加载项到内存:
IEnumerable<Item> = items
.Select(item => new
{
Item = item,
SubItems = item.SubItems.Where(sub => sub.ID = 1)
}
)
.ToList()
.Select(row =>
{
var item = row.Item;
item.SubItems = row.SubItems;
return item;
}
);
选项2:返回类的一个新实例(这看起来你不想做)
IQueryable<Item> items = items
.Select(item => new Item
{
SubItems = item.SubItems.Where(sub => sub.ID == 1),
OtherProp = item.OtherProp
/*etc for the other properties on Item*/
}
);
选项3:添加另一个属性到你的班级。我至少推荐这个。请注意,您的查询仍然会返回所有子项在这里,当你访问SubItemsWithIdOne
class Item
{
private List<SubItem> SubItems { get; set; }
private List<SubItem> SubItemsWithIdOne
{
get
{
return this.SubItems.Where(sub => sub.ID == 1);
}
}
}
方案4:添加引用它的父Item
上SubItem
的属性。然后返回一个列表SubItem
。通过这种方式,您可以在SubItems
和Items
之间符合条件。
...如果你有IEnumerable
工作,你可以这样做:
IEnumerable items = items
.Select(item =>
{
item.SubItems.Where(sub => sub.ID = 1);
return item;
}
);
为什么不在发出查询时只包含where子句? –
好问题。原因是我正在寻找使用假数据对我的过滤器进行单元测试,而不是依赖于随时间改变状态的数据库 –