0

如何通過wl.WishlistID對此查詢的結果進行分組?linq顯示在視圖中的結果 - 如何應用分組

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 

但我似乎不能夠通過使用克至訪問任何屬性將[PropertyName]

這種分組達到或多或少我想要什麼,但我想將結果轉換爲新的或匿名的類型,而不是返回整個對象。

group wl by wl.WishlistID into g 

gIGrouping<typeof(wl.WishlistID),typeof(wl)>型的,這基本上是所有wl的的使用相同的密鑰wl.WishlistID集合:

var results = context.WishlistItems.GroupBy(x => x.Wishlist). 
       Select(group => new { wl = group.Key, items = group.ToList() }).ToList(); 

回答

1

,因爲當你做分組,您不能訪問的g屬性。換句話說,您不能訪問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; 
    } 
}