LINQ groups by then orders result groups

.net c# entity-framework linq

Question

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?

1
20
5/10/2012 9:08:12 AM

Accepted Answer

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.

42
4/1/2015 2:11:52 PM

Popular Answer

In fact, you don't want to group by short code, you want to order by them. So the following query should do the trick:

rawData.Provider.CreateQuery<PDFDocument>(qb.rootExperession)
.ToList()
.OrderBy(b => b.ShortCode)
.ThenBy(b => b.UploadDate)
.ToList()

Edit If you really want to use a GroupBy, you can do so this way:

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

But I discourage it. There is no point creating groups if you do not want groups in the first place!

Second edit

I did not get you wanted the groups ordered by UpdateTime too. It complicates a little the query:

rawData.Provider.CreateQuery<PDFDocument>(qb.rootExperession)
.ToList()
.GroupBy(b => b.ShortCode)
.Select(grouping => grouping.OrderByDescending(b => b.UploadDate))
.OrderByDescending(grouping => grouping.First().UploadDate)
.SelectMany(grouping => grouping)
.ToList()


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow