Bora
Bora

Reputation: 127

Reordering the linq statement after group by

Basicly, i have a statement which is like that

Contents
.Where(x=>x.CategoryId==5 && x.Status==1)
.GroupBy(q=>q.VersionId)
.OrderByDescending(q=>q.Key)
.Take(100)  
.Select(q => new { VersionId = q.Key, MajorVersion = q.Max(x => x.MajorVersion) })

At the moment, it looks like below. But i want to reorder MajorVersion field as a descending...

VersionId     MajorVersion
387276        2
365015        1
355427        3
369865        1

How do i do that?

Upvotes: 0

Views: 64

Answers (2)

Trevor Pilley
Trevor Pilley

Reputation: 16413

Select returns an IEnumerable so you can do further sorting/ordering etc after.

Contents
.Where(x => x.CategoryId == 5 && x.Status == 1)
.GroupBy(q => q.VersionId)
.OrderByDescending(q => q.Key)
.Take(100)  
.Select(q => new { VersionId = q.Key, MajorVersion = q.Max(x => x.MajorVersion) })
.OrderByDescending(x => x.MajorVersion);

Upvotes: 2

SLaks
SLaks

Reputation: 887777

Just move the OrderByDescending after the Select.
You will then be able to sort by the fields in the select. (since you'll be calling OrderByDescending on the IQueryable of anonymous types returned by Select())

Upvotes: 1

Related Questions