Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to group a class by date and select Max(Date), primary-key and foreign-key?

I need to reduce data from a class as given below (PK … primary key, FK … foreign key):

enter image description here

Using linq I tried several variations as given below

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var groupedClass = from record in records
               group new {
                   record.Date
               }
               by new{
                   record.FK,
                   //record.PK  //  when included then resulting data are not distinct regarding FK
               }
               into g
               select new{
                   MaxDate = g.Max(r => r.Date),
                   SelectedFK = g.key.FK,
                   //SelectedPK = g.key.PK    // gives an error when PK is not inluced in by new
               };

but I can not get distinct PK, FK and Max(date) into the grouped data set. Please help!

>Solution :

Group by FK, then use MaxBy to select the record with the maximum date in each group:

var groupedClass = records
    .GroupBy(record => record.FK)
    .Select(grp => grp.MaxBy(record => record.Date));

Working example: https://dotnetfiddle.net/9Pe4Z4


If you’re not using .NET 6 then MaxBy won’t be available, so you could use OrderByDescending and First instead:

var groupedClass = records
    .GroupBy(record => record.FK)
    .Select(grp => grp.OrderByDescending(record => record.Date).First());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading