如何通过wl.WishlistID?
对此查询的结果进行分组var projected = (from wl in context.Wishlists.Where(x => x.UserId == 6013)
from wli in wl.WishlistItems
select new wishListProjection
{
wlId = wl.WishlistID,
wlUserId = (int)wl.UserId,
wlDesc = wl.description,
wlTitle = wl.Title,
wliWishlistItemID = wli.WishlistItemID,
wliQtyWanted = (int)wli.QtyWanted,
wliPriceWhenAdded = wli.PriceWhenAdded,
wliDateAdded = (DateTime)wli.DateAdded,
wliQtyBought = (int)wli.QtyBought,
}).ToList();
这会返回我想要的结果,但我希望能够在视图中迭代它们而不重复父级Wishlist对象。 我试过添加一行:
group wl by wl.WishlistID into g
但我似乎无法使用g。[propertyname]
访问任何属性这种分组或多或少地实现了我想要的,但我希望将结果转换为新的或匿名的类型,而不是返回整个对象。
var results = context.WishlistItems.GroupBy(x => x.Wishlist).
Select(group => new { wl = group.Key, items = group.ToList() }).ToList();
答案 0 :(得分:1)
您无法访问g
的属性,因为进行分组时:
group wl by wl.WishlistID into g
g
的类型为IGrouping<typeof(wl.WishlistID),typeof(wl)>
,它实际上是具有相同键wl
的所有wl.WishlistID
的集合。换句话说,您无法访问g
的属性,因为g
不是单个实体,而是这些实体的集合。
对于你的第二个分组,你说你想创建一个匿名类型而不是整个对象。您可以先执行选择,然后分组:
var results = context.WishlistItems
.Select(x => new { })
.GroupBy(x => x.PropertyOfProjection)
.Select(group => new { wl = group.Key, items = group.ToList() }).ToList();
或者,在第一个示例中使用嵌套的子查询:
var projected = (from x in
(from wl in context.Wishlists.Where(x => x.UserId == 6013)
from wli in wl.WishlistItems
select new wishListProjection
{
wlId = wl.WishlistID,
wlUserId = (int)wl.UserId,
wlDesc = wl.description,
wlTitle = wl.Title,
wliWishlistItemID = wli.WishlistItemID,
wliQtyWanted = (int)wli.QtyWanted,
wliPriceWhenAdded = wli.PriceWhenAdded,
wliDateAdded = (DateTime)wli.DateAdded,
wliQtyBought = (int)wli.QtyBought,
})
group x by w.wlId into g).ToList();
我不确定迭代的意思而不重复父级Wishlist对象,因为无论何时在Linq中创建分组,你仍然必须有一个嵌套的foreach
:
foreach (var x in grouping)
{
x.Key;
foreach (var y in x)
{
y.Property;
}
}