Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)))
like image 427
endyourif Avatar asked Jan 20 '26 00:01

endyourif


1 Answers

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()).

like image 134
Mansfield Avatar answered Jan 22 '26 18:01

Mansfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!