LINQ groups by then orders result groups

.net c# entity-framework linq

Question

The three columns in my table are ID, ShortCode, and UploadDate.

I want to use LINQ to arrange those groups and produce a list after grouping the results by shortcode (while keeping all the results).

I have these things:

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

The items inside each group should be ordered by UploadDate, and the groups themselves should be sorted such that the group with the most recent document in it is at the top. I want to provide all results, categorized by ShortCode.

Anybody have any idea whether this is even conceivable?

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 ought to

  • The items are arranged by upload date (descending so newest first)
  • Then group them by short code so that the items are still ordered inside each group.
  • There is no need to reorder since the groups are still in decreasing order.
  • Concatenate the outcomes to create a single list.

If performance is a concern, you could do better via

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, as opposed to sorting everything first and then grouping, sorts the contents of each group independently.

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

Popular Answer

In actuality, you want to arrange by short codes rather than group by them. Therefore, the following inquiry ought to work:

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

Edit You may use a GroupBy in the following manner if you truly want to:

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

But I advise against it. If you don't want groups to begin with, there is no purpose in forming them.

2nd revision

I was not aware that you also wanted the groups to be sorted by UpdateTime. It makes the problem a bit trickier:

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