使用LINQ to实体加入前1

时间:2015-02-10 15:56:29

标签: c# linq linq-to-entities

我有一个实体列表,每个实体都有0> n相关评论。如果每个实体都存在,我想加入最新的评论。然后,我想返回最新评论的状态,如下所示,但无法通过CreatedDate Descending将lstReviews过滤到前1名。

 var lstMainEntity = this.service.GetAllMainEntities();
 var lstReviews = this.service.GetReviews();

 var lst = from e in lstMainEntity 
           from review in lstReviews.Where(r => r.EntityID == e.EntityID).DefaultIfEmpty()   
  select new 
  {
      ID = e.EntityID,
      ReviewStatus = review != null ? review.IsComplete ? "Complete" : "Active"
  }

我怎样才能做到最好?

1 个答案:

答案 0 :(得分:0)

我假设lstMainEntitylstReviewsIQueryable<..>。如果它们是IEnumerable<..>,则必须在ReviewStatus作业中进行空检查。 (如果是IQueryable

,性能应该更快
  var lst = from e in lstMainEntity 
            let review = lstReviews.Where(r => r.EntityID == e.EntityID)
                                   .OrderByDescending(r => r.CreatedDate)
                                   .FirstOrDefault()
  select new 
  {
      ID = e.EntityID,
      ReviewStatus = review.IsComplete ? "Complete" : "Active"
  }