frenchie
frenchie

Reputation: 51937

linq-to-sql .All() or .Any() to find all items that match criteria

I have a table that looks like this:

| FruitID | BasketID | FruitType |
|   23    |    2     |    1      |
|   24    |    5     |    1      |  
|   25    |    2     |    1      |
|   26    |    5     |    2      |

I'm writing a query where I'm passing a list of BasketIDs and I want to get back a new list of BasketIDs that contains only baskets that have FruitID where all FruitTypes are equal to 1. For instance, if I pass in BasketIDs 2 and 5, I get back only 2 because basket 5 has FruitID 26 that's of FruitType 2.

This is what I have:

var TheQuery = (from f in MyDC.TableFruits
                where TheListOfBasketIDs.Contains(f.BasketID) &&
                // need help here 
                select f.BasketID).ToList();

Thanks for your suggestions on how to write the filter.

Upvotes: 2

Views: 2757

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Group fruits by BasketID to verify all fruits from basket have FruitType equal to 1:

var TheQuery = (from f in MyDC.TableFruits                  
                group f by f.BasketID into g
                where TheListOfBasketIDs.Contains(g.Key) &&
                      g.All(x => x.FruitType == 1)
                select g.Key).ToList();

Upvotes: 5

Related Questions