OrderByDescending在嵌套的linq语句中不起作用

时间:2013-03-11 12:47:12

标签: c# linq

在Linqpad中,我可以看到正确的列表。但是在代码中,在放入列表集合之后,order by对BeginDate不起作用。如果我使用BeginDate和Max,它可以工作。我不明白我哪里错了?

            var templist =  contentRepository
                       .Get(q => (q.Status == (int)StatusEnum.Active) &&     
                           (q.CategoryId == category.GetHashCode() || q.Category.ParentId == category.GetHashCode())                   
                           && q.MinorVersion == 0
                           && q.MajorVersion > 0) 
                       .GroupBy(q => q.VersionId)
                       .OrderByDescending(q => q.Key)
                       .Select(q => new 
                       {
                           VersionId        = q.Key,
                           Id               = q.Max(x => x.Id),
                           MajorVersion     = q.Max(x => x.MajorVersion), 
                           UpdatedAt        = q.Max(x => x.UpdatedAt), 
                           //BeginDate        = q.Max(x=>x.BeginDate),
                           BeginDate        = (q.OrderByDescending(x => x.Id).Take(1).Select(x=>x.BeginDate)).First(),
                           Title = (q.OrderByDescending(x => x.Id).Take(1).Select(x => x.Title)).First(),
                           ShowOnHomePage   = (q.OrderByDescending(x => x.Id).Take(1).Select(x=>x.ShowOnHomePage)).First()
                        })
                       .OrderByDescending(x => x.BeginDate)                           
                       .Take(maxItemCount)
                       .ToList();

            List<ContentEntity> contents = new List<ContentEntity>();

        templist.ForEach(q => contents.Add(
                                         contentRepository
                                        .Get(x => x.VersionId == q.VersionId && x.MajorVersion == q.MajorVersion && x.MinorVersion == 0)
                                        .FirstOrDefault()                                        
                                        ));


        return contents.Where(q => q.ShowOnHomePage == true)
                       .OrderByDescending(q => q.MajorVersion)
                       .OrderByDescending(q => q.BeginDate)
                       .Take(maxItemCount)
                       .ToList();

1 个答案:

答案 0 :(得分:2)

您的订单是Id,而不是BeginDate

的等效代码
q.Max(x => x.BeginDate)

将是

q.OrderByDescending(x => x.BeginDate).Take(1).Select(x => x.BeginDate).First()

或简化

q.OrderByDescending(x => x.BeginDate).First().BeginDate