score:3

Accepted answer

You can use GroupBy:

var products = _context.Product
    .Where(x => x.IsActive)
    .GroupBy(x => x.SecondaryId)
    .Select(grp => grp.OrderByDescending(x => x.CreatedOn).First())
    .ToDTOs();

Then within each group, select the object with highest CreatedOn.

score:3

You'll need to group by the Secondary ID's, then take only the first row from each grouping, like so:

var products = _context.Product
                       .Where(x => x.IsActive)
                       .GroupBy(x => x.SecondaryID)
                       .Select(x => x.OrderByDesc(y => y.CreatedOn).First())
                       .OrderBy(x => x.CreatedOn)
                       .ToDTOs();

EDIT: missed that you wanted specifically the newest from each grouping - the OrderByDesc in the Select statement should do the trick


Related Query

More Query from same tag