簡體   English   中英

如何獲得Linq組中的最后一個實體和實體數

[英]How to get last entity and count of entities in Linq group by

我想獲得我產品的評論數和最后評論數。

所以這是我的linq to SQL代碼:

from c in Filter<Comment>().OrderByDescending(m => m.Date)
join p in Filter<Product>() on c.ProductId equals p.Id
join u in Context.ShopUsers on c.CustomerId equals u.Id
group c by c.ProductId into g
select new CommentViewModel
                      {
                          Comment = g.OrderByDescending(m => m.Date).FirstOrDefault(),
                          Product = g.OrderByDescending(m => m.Date).FirstOrDefault()
                                  .Product.Name,
                          UserName = g.OrderByDescending(m => m.Date).FirstOrDefault()
                              .Customer.RealUserName,
                          Name = g.OrderByDescending(m => m.Date).FirstOrDefault()
                          .Customer.FirstName + " " +
                          g.OrderByDescending(m => m.Date).FirstOrDefault()
                          .Customer.LastName,
                          Comments = g.Count()
                      };

我想避免使用此重復代碼來獲得第一個實體。

我怎樣才能做到這一點?

您可以簡單地引入let子句並存儲第一個注釋,如下所示:

from c in Filter<Comment>().OrderByDescending(m => m.Date)
join p in Filter<Product>() on c.ProductId equals p.Id
join u in Context.ShopUsers on c.CustomerId equals u.Id
group c by c.ProductId into g
let firstComment = g.OrderByDescending(m => m.Date).FirstOrDefault()
select new CommentViewModel
        {
            Comment = firstComment,
            Product = firstComment.Product.Name,
            UserName = firstComment.Customer.RealUserName,
            Name = firstComment.Customer.FirstName + " " + firstComment.Customer.LastName,
            Comments = g.Count()
        };

使用臨時投影:

(from c in Filter<Comment>().OrderByDescending(m => m.Date)
join p in Filter<Product>() on c.ProductId equals p.Id
join u in Context.ShopUsers on c.CustomerId equals u.Id
group c by c.ProductId into g
select new {
  LatestComment=g.OrderByDescending(m => m.Date).FirstOrDefault(),
  Comments=g.Count()
})
.Select(c=>new CommentViewModel {
  Comment=c.LatestComment,
  Product=c.LatestComment.Product.Name,
  UserName=c.LatestComment.RealUserName,
  Name=c.LatestComment.Customer.FirstName+" "+c.LatestComment.Customer.LastName,
  Comments=c.Comments
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM