I have a LINQ query:
Elements.Join(ElementStates,
element => element.ElementID,
elementState => elementState.ElementID,
(element , elementState ) => new { element, elementState })
OK, so each Element
has an ElementState
associated to it. However there can be multiple states for each element for historical purposes, marked by a DateModified
column. In this query, I would like to return only the most recent ElementState
for each Element
.
Is such a thing possible, using LINQ?
EDIT:
Credit to Gilad Green for their helpful answer.
I have converted it to Method syntax for anyone else who would like to see this in the future:
Elements.GroupJoin(ElementStates,
element => element.ElementID,
elementState => elementState.ElementID,
(element, elementState) =>
new { element, elementState = elementState.OrderByDescending(y => y.DateModified).FirstOrDefault() });