What is LINQ to select the last item from multiple versions?

I have a class like the following:

public class Invoice
{
    public int InvoiceId {get;set;}
    public int VersionId {get;set;}
}

Each time it changes Invoice, the value VersionIdincreases, but InvoiceIdremains unchanged. So given IEnumerable<Invoice>that has the following results:

InvoiceId VersionId
1         1
1         2
1         3
2         1
2         2

How can I get only the results:

InvoiceId VersionId
1         3
2         2

those. I want only invoices from results that have the latest VersionId. I can easily do this in T-SQL, but I cannot work out the correct LINQ syntax for my whole life. I am using Entity Framework 4 Code First.

+3
source share
3 answers

VersionId, InvoiceId, . :

var query = list.OrderByDescending(i => i.VersionId)
                .GroupBy(i => i.InvoiceId)
                .Select(g => g.First());

EDIT: , Max?

var query = list.GroupBy(i => i.InvoiceId)
                .Select(g => g.Single(i => i.VersionId == g.Max(o => o.VersionId)));

FirstOrDefault SingleOrDefault Single... , Single .

+1

EDIT: LINQ to Entities. , , , , , ?


1:

var latestInvoices = invoices.GroupBy(i => i.InvoiceId)
                             .Select(group => group.OrderByDescending(i => i.VersionId)
                                                   .FirstOrDefault());

EDIT: "" "FirstOrDefault", LINQ to Entities "".


2:

var invoices = from invoice in dc.Invoices
               group invoice by invoice.InvoiceId into invoiceGroup
               let maxVersion = invoiceGroup.Max(i => i.VersionId)
               from candidate in invoiceGroup
               where candidate.VersionId == maxVersion
               select candidate;
+1

:

var h = from i in Invoices
        group i.VersionId by i.InvoiceId into grouping
        select new {InvoiceId = grouping.Key, VersionId = grouping.Max()};

, . IQueryable<Invoice>. , , .

var maxVersions = from i in Invoices
                  group i.VersionId by i.InvoiceId into grouping
                  select new {InvoiceId = grouping.Key, 
                              VersionId = grouping.Max()};

var latestInvoices =  from i in Invoices
                      join m in maxVersions 
                      on new {i.InvoiceId, i.VersionId} equals 
                         new {m.InvoiceId, m.VersionId}
                      select i;
+1

Source: https://habr.com/ru/post/1775687/


All Articles