我有一个实体列表,每个实体都有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"
}
我怎样才能做到最好?
答案 0 :(得分:0)
我假设lstMainEntity
而lstReviews
为IQueryable<..>
。如果它们是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"
}