简体   繁体   中英

LINQ query to get record with maximum values

I have following values in a table and I need a LINQ query which satisfies the conditions below.

Select a single record, which has the maximum RevOrder. If there are multiple records with same maximum RevOrder, then select the record with maximum RevDate If RevDate's are equal too then get the record with maximum RevisionStatusID.

RevisionStatusID      RevDate         RevOrder
1                     12/01/2012      0
2                     14/02/2013      1
3                     10/02/2013      2
4                     11/01/2013      2
5                     11/01/2013      3

I tried the below query but it gives an error.

var DocRevIDs = (from tbh in context.tblDocumentHeaders
                 join tbr in context.tblDocumentRevisions
                 on tbh.DocumentHeaderID equals tbr.DocumentHeaderID
                 where tbh.DocumentHeaderID == tb.DocumentHeaderID
                 select tbr).Max(o => new { o.RevOrder,o.RevisionDate,o.DocumentRevisionID });

Unable to process the type '<>f__AnonymousType52 3[System.Nullable 1[System.Double],System.Nullable`1[System.DateTime],System.Int32]', because it has no known mapping to the value layer.

Instead of trying to use Max() , use a combination of orderby clauses and then use FirstOrDefault() . This would be the approach you would take to do it via straight SQL.

So that would give you something similar to:

var docRevision = (from tbh in context.tblDocumentHeaders
                 join tbr in context.tblDocumentRevisions
                 on tbh.DocumentHeaderID equals tbr.DocumentHeaderID
                 where tbh.DocumentHeaderID == tb.DocumentHeaderID
                 orderby tbr.RevOrder descending, tbr.RevisionDate descending, tbr.DocumentRevisionID descending
                 select tbr).FirstOrDefault();

you should Order the records in the linq:

var DocRevIDs = (from tbh in context.tblDocumentHeaders
             join tbr in context.tblDocumentRevisions
             on tbh.DocumentHeaderID equals tbr.DocumentHeaderID
             where tbh.DocumentHeaderID == tbr.DocumentHeaderID
             orderby tbr.RevOrder descending, tbr.RevDate descending, tbr.RevisionStatusID descending
             select tbr).First();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM