如何将此查询的结果按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();发布于 2013-09-25 12:51:54
不能访问g的属性,因为在进行分组时:
group wl by wl.WishlistID into gg是IGrouping<typeof(wl.WishlistID),typeof(wl)>类型的,本质上是具有相同键wl.WishlistID的所有wl的集合。换句话说,您不能访问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;
}
}https://stackoverflow.com/questions/19002763
复制相似问题