简体   繁体   中英

Linq where clause for collection in a collection

I have a list of invoices with a list of payment schedules and the payment schedules have a collection of journals.

Invoices -> Payment Schedules -> Payment Schedule Journals

I want to get all invoices that have a Payment Schedule Journal status of Due and Overdue.

I can't get the Linq statement to get the second level deep.

I'm trying something like this with no success (statuses being a list of status):

i => i.PaymentSchedules.Any(p => p.PaymentScheduleJournals.Where(ps => statuses.Contains(ps.Status)))

Try this:

var invoices = Invoices.Where(
               i => i.PaymentSchedules.Where(
                    p => p.PaymentScheduleJournals.Where(
                         ps => statuses.Contains(ps.Status))
                    .Any())
               .Any());

Remember that Any() returns true or false if any matching items are found, not the item itself. So using Any() where you have it in your code wouldn't actually return any data.

Also, this query will return Payment Schedules if run by itself (not sure if this is only part of the expression you had in your question), not the invoices.

Further explanation: This query looks for any PaymentSchedules that have a PaymenScheduleJournal with a status in the list of valid statuses. Remember that a call to Where() will return the actual query items, but in the case of the journals, that's not what we want: we want all the schedules that have a valid journal. That's what the Any() gives us - Any schedules that have a journal. We repeat the same process to load any invoices that have a valid payment schedule, because invoices are what we're actually after (notice no third call to Any() ).

You could use the SelectMany projection operator.

var validStatuses = new List<string>{"Due", "Overdue"};

var invoices = allInvoices
    .Select(invoice => invoice.Schedules
        .SelectMany(paymentSchedule => paymentSchedule.Journals)
        .Where(journal => validStatuses.Contains(journal.Status)));

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