我有下面的物件類。如何設定 linq 查詢來過濾myItems串列以僅回傳串列中ItemGroups帶有 a 的CategoryId專案categories?因此,在下面的示例資料中,我希望我的 linq 查詢僅回傳帶有的專案,因為它是串列ItemId = 1中唯一具有帶有 a 的專案組的專案。CategoryIdcategories
我嘗試了以下方法,但這似乎不起作用:
myItems.Where(i => categories.Contains(i.ItemGroups.Select(g => g.CategoryId)))
public ItemGroup{
int ItemGroupId
int CategoryId
}
public class Item(
int ItemId;
List<ItemGroup> ItemGroups
)
List<int> categories {2,5,7}
List<Item> myItems = [
{
ItemId = 1,
ItemGroups = [
{
ItemGroupId = 1,
CategoryId = 1
},
{
ItemGroupId = 2,
CategoryId = 2
},
]
},
{
ItemId = 2,
ItemGroups = [
{
ItemGroupId = 3,
CategoryId = 3
},
{
ItemGroupId = 4,
CategoryId = 4
},
]
}
]
uj5u.com熱心網友回復:
您可以嘗試在謂詞中使用AnyonItemGroupWhere
myItems.Where(i => i.ItemGroups.Any(g => categories.Contains(g.CategoryId)));
uj5u.com熱心網友回復:
這是一種方法,其中 Linq 操作嵌套一層,而不是兩層。
對于每個Item,.IntersectBy()用于確定其存在于 中的ItemGroups集合。如果存在任何此類,則將包括在內。CategoryIdcategoriesItemGroupItem
IEnumerable<Item> filteredItems = myItems
.Where(i => i.ItemGroups
.IntersectBy(categories, gr => gr.CategoryId)
.Any());
示例小提琴在這里。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/454031.html
上一篇:Linq-選擇帶有計數的列
