0

如何按 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();
4

1 回答 1

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;
    }
}
于 2013-09-25T12:51:54.657 回答