Richard West
Richard West

Reputation: 2226

Sorting output from Linq with group by

The linq query below is not returning results that have been ordered by the sequence field in decending order. Instead the results are returned without regard to the orderby:

var qr = from l in reports.layouts
    where l.job == jobNumber
    orderby l.sequence descending
    group l by l.filename;

However the code below is able to return the results grouped by the filename field, and ordered decending by the sequence field:

var qr = reports.layouts
   .Where(l => l.job == jobNumber)
   .OrderBy(l => l.filename)
   .GroupBy(l => l.filename, (l, c) => c.OrderByDescending(x => x.sequence));

Can anyone offer any insight as to how the first query should be written to return the results in the desired descending sequence?

Upvotes: 1

Views: 140

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564363

Grouping destroys the order. Your two queries are not the same.

The first translates into something more like:

var qr = reports.layouts
   .Where(l => l.job == jobNumber)
   .OrderByDescending(l => l.sequence)
   .GroupBy(l => l.filename);

Since the GroupBy happens after the ordering, it effectively destroys the ordering.

Personally, this is one case where I find the method chain syntax you've used much more clear in terms of intent than an equivalent query syntax.

Upvotes: 1

Amy B
Amy B

Reputation: 110071

var qr =
  from l in reports.layouts
  where l.job == jobNumber
  group l by l.filename into g
  orderby g.Key descending
  select
    from x in g
    orderby x.sequence descending
    select x;

Upvotes: 1

Related Questions