linq结果显示在视图中 - 如何应用分组

时间:2013-09-25 10:44:52

标签: asp.net-mvc-4 linq-to-entities entity-framework-5 grouping

如何通过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();

1 个答案:

答案 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;
    }
}