简体   繁体   中英

linq query selecting all elements of certain value but none of another value

I have a table that looks somewhat like this:

| FruitID | BasketID | FruitType |

I'm passing in the query a list of BasketIDs and I want the list of FruitIDs that are within the BasketID AND that are only of a certain FruitType (values can only 1 or 2).

This is what I have:

var TheQuery = (from a in MyDC.MyTable

                where TheBasketIDs.Contains(a.BasketID) &&
                      a.FruitType == 1 // need help here

                select a.FruitID).ToList();

I'm having some difficulty expressing the second where condition. I want the FruitIDs where all the FruitType are all 1s and none are 2s.

| FruitID | BasketID | FruitType |
|   23    |    2     |    1      |
|   23    |    5     |    1      |  
|   19    |    2     |    1      |
|   19    |    5     |    2      |

For instance, Fruit 23 is ok because its FruitType is always 1 but Fruit 19 isn't ok because it also has a FruitType of 2, even if the list of TheBasketIDs I'm passing in doesn't contain a 5.

One way to do this would be to group by fruit id, and then examine the resultant groups with LINQ expressions:

var ids = MyDC.MyTable
    .GroupBy(r => r.FruitID)
    // The following condition examines g, the group of rows with identical FruitID:
    .Where(g => g.Any(item => TheBasketIDs.Contains(item.BasketID))
             && g.Any(item => item.FruitType == 1)
             && g.All(item => item.FruitType != 2))
    .Select(g => g.Key);

This produces the list of FruitID s of your desired type.

EDIT: (in response to a comment below)

Type is only 1 or 2 but never 3

Then you can simplify your query as follows:

var ids = MyDC.MyTable
    .GroupBy(r => r.FruitID)
    // The following condition examines g, the group of rows with identical FruitID:
    .Where(g => g.Any(item => TheBasketIDs.Contains(item.BasketID))
              // When there is no 3-rd state, FruitType==1 will keep FruitType==2 out
             && g.All(item => item.FruitType == 1))
    .Select(g => g.Key);
var TheQuery = (from a in MyDC.MyTable
                group a by a.FruitID into g
                where g.Any(b => TheBasketIDs.Contains(b.BasketID)) && g.All(b => b.FruitType == 1)
                select g.Key).ToList();

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