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?
Found answer on MSDN: Yes.
GroupBy(student => student.Name) . Select(group => new { Name = group. Key, Students = group. OrderByDescending(x => x.
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.
Try
rawData.Provider.CreateQuery<PDFDocument>(qb.rootExperession) .AsEnumerable() .OrderByDescending(d => d.UploadDate) .GroupBy(d => d.ShortCode) .SelectMany(g => g) .ToList();
This should
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With