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

时间:2015-12-13 06:41:07

标签: c# entity-framework linq

我想了解我的产品评论和最后评论。

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

我想避免使用这个重复代码来获取第一个实体。

我该怎么做?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

使用临时投影:

(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
});