Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ group by then order groups of result

Tags:

I have a table that has the following 3 columns, ID, ShortCode, UploadDate.

I want to use LINQ to group the results by shortcode (and keep all the results) then order those groups and return a list.

I have the following:

 rawData.Provider.CreateQuery<PDFDocument>(qb.rootExperession) .ToList<PDFDocument>(). GroupBy(b=>b.ShortCode) .SelectMany(b=>b).ToList<PDFDocument>() 

I want to return all results, grouped by ShortCode, the items within each group sorted by UploadDate and the groups sorted so the one that has the most recent document in it first.

Does anyone know if this is even possible?

like image 935
Ketchup Avatar asked May 10 '12 09:05

Ketchup


People also ask

Does LINQ GroupBy keep order?

Found answer on MSDN: Yes.

How do I sort by group in C#?

GroupBy(student => student.Name) . Select(group => new { Name = group. Key, Students = group. OrderByDescending(x => x.

How does GroupBy work in LINQ?

Group by works by taking whatever you are grouping and putting it into a collection of items that match the key you specify in your group by clause.


1 Answers

Try

rawData.Provider.CreateQuery<PDFDocument>(qb.rootExperession)     .AsEnumerable()     .OrderByDescending(d => d.UploadDate)     .GroupBy(d => d.ShortCode)     .SelectMany(g => g)     .ToList(); 

This should

  • Order the items by upload date (descending so newest first)
  • Then group them by short code - so within each group the items are still sorted
  • The groups are still in descending order, so no need to order again
  • Finally concatenate the results into a single list

If performance is an issue you many be better off doing

rawData.Provider.CreateQuery<PDFDocument>(qb.rootExperession)     .AsEnumerable()     .GroupBy(d => d.ShortCode)     .Select(g => g.OrderByDescending(d => d.UploadDate))     .OrderByDescending(e => e.First().UploadDate)     .SelectMany(e => e)     .ToList(); 

which sorts the contents of each group separately rather than sorting everything first and then grouping.

like image 115
Rawling Avatar answered Jan 08 '23 12:01

Rawling