How do I get a list of companyIDs who shipped all their orders in linq?
Scenario: Each company got a bunch of customers and orders for customers. Here from the below tables, CompanyB and CompanyC has shipped all the orders to customers and I want to get those ID from a linq query.
3 tables involved Company, Customers and Orders
Company
CompanyID CompanyName
1 CompanyA
2 CompnayB
3 CompnayC
Customers
CustomerID CustomerName CompanyID
1 CustomerA 1
2 CustomerB 2
3 CustomerC 2
4 CustomerD 2
5 CustomerE 1
6 CustomerF 2
7 CustomerG 3
Orders
OrderID CustomerID Shipped
1 2 1
2 3 1
3 4 1
4 6 1
5 1 0
6 7 1
Here is what I tried and I’m not getting the right output
var IDs = Company.Where(co => co.Customers.Any(cu => cu.Orders.Any(o => o.shipped))).ToList();
Any help is much appreciated..
4
Answers
Try this:
I haven’t tried running this, but what if I try
All
instead ofAny
? Probably, if you are working with a database on EF and not just a collection, you should have lazy loading enabled.And, since you only need the
ID
, I addedSelect
you can join two tables with linq like below :
and you can use fluentApi :
You can rely on
SelectMany
as an alternative to doubleAll
calls:This feels slightly more semantic IMHO for your requirement.