James Wilson
James Wilson

Reputation: 5150

Selecting max revision with Linq statement

I've looked over some other answers and none seemed to be exactly what I'm looking for and I could not get further with those questions than I currently am.

I have a single table that houses all of our documents and revisions.

I currently have this Linq:

from v in IPACS_Versions
where v.DateApproved == null
group v by v.DocumentID into g
select g.Max(t => t.Revision)

This correctly gives me the items that need revisions, however I need to select all of the fields and currently it is only selecting the Revision field. I am very new to Linq, how can I change this?

More Detail in case my above code is completely wrong.

I need to select the entire row for the max revision for each document. The primary key is documentId, and each documentId can have many different revisions, I need the most recent one. The other criteria is there is a field dateApproved that is null if it has not been approved yet, so the max revision or any item that has not been approved.

Upvotes: 0

Views: 289

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500785

If this is querying against a database, you probably want:

from v in IPACS_Versions
where v.DateApproved == null
group v by v.DocumentID into g
select g.OrderByDescending(t => t.Revision).First()

If it's running locally (LINQ to Objects), you can use the MaxBy method of MoreLINQ:

from v in IPACS_Versions
where v.DateApproved == null
group v by v.DocumentID into g
select g.MaxBy(t => t.Revision)

Upvotes: 4

Related Questions