我理解你的問題,你想返回所有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子句? –
好問題。原因是我正在尋找使用假數據對我的過濾器進行單元測試,而不是依賴於隨時間改變狀態的數據庫 –