robin
robin

Reputation: 497

Linq Collection instersection List/Array

Consider the following list:

List<long> listOfIDs = new List<long> { 1, 2, 3, 4 };

[(Product) 1 Pineapple - (Supplier) Fruit Inc / Marketplace Inc]>

[2 Strawberry - Fruit Inc]>

[3 Coke - Super Drinks Inc / Marketplace Inc]>

[4 Orange Juice - Super Drinks Inc]

db.Table.Where(a => a.SubTable.All(b => listOfIds.Contains(b.SubTableId)))

While I've selected Products 1 and 2, I should get only Fruit Inc as a Supplier. When I include Coke into my list, I don't want to see any supplier anymore because there is no Supplier that represents these 3 products at the same time.

Expected Outputs Scenarios:

Selected Products: 1, 2 Expected Result: Fruit Inc

1, 3 Marketplace Inc

1, 2, 3 Empty.

1, 3, 4 Empty.

3, 4 Super Drinks Inc

Upvotes: 0

Views: 58

Answers (1)

Batman
Batman

Reputation: 11

// change All to Select if you want list of each bool
     db.Table.All(a => listOfIds.Contains(a.SubTableId));

This should do the trick if you want to check if listOfIds exists in the db since you mentioned ContainsAll.

If you want to get the entities from db with listOfIds then this should do it.

 db.Table.Where(a => listOfIds.Contains(a.SubTableId)).ToList;

Upvotes: 1

Related Questions