简体   繁体   中英

OrderByDescending doesn't work in nested linq statement

In Linqpad, i can see the correct list. But in code, after putting in the list collection, order by doesn't work for BeginDate. If i use BeginDate with Max, it works. I don't understand where i am wrong?

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

You are ordering by Id , not by BeginDate . Equivalent code for

q.Max(x => x.BeginDate)

Will be

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

Or simplified

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM