如何通过获取Linq组中的最后一个实体和实体数

本文关键字:实体 最后一个 何通过 获取 Linq | 更新日期: 2023-09-27 18:26:38

我想得到我的产品的评论数和最后一条评论。

这是我的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()
                      };

为了获得第一个实体,我想避免这种重复的代码。

我该怎么做?

如何通过获取Linq组中的最后一个实体和实体数

您可以简单地引入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
});