linq查询选择具有特定值的所有元素但不选择其他值

fre*_*hie 2 c# linq linq-to-sql

我有一个看起来像这样的表:

| FruitID | BasketID | FruitType |
Run Code Online (Sandbox Code Playgroud)

我在查询中传递了一个列表,BasketIDs我希望它的列表FruitIDsBasketIDAND中只是一定的FruitType(值只能是1或2).

这就是我所拥有的:

var TheQuery = (from a in MyDC.MyTable

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

                select a.FruitID).ToList();
Run Code Online (Sandbox Code Playgroud)

我在表达第二个where条件时遇到了一些困难.我希望FruitIDs所有的FruitType全部都是1,而没有2是2.

| FruitID | BasketID | FruitType |
|   23    |    2     |    1      |
|   23    |    5     |    1      |  
|   19    |    2     |    1      |
|   19    |    5     |    2      |
Run Code Online (Sandbox Code Playgroud)

例如,Fruit 23是好的,因为它FruitType总是1,但Fruit 19不好,因为它也有FruitType2,即使TheBasketIDs我传入的列表不包含5.

das*_*ght 8

执行此操作的一种方法是按果ID分组,然后使用LINQ表达式检查结果组:

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);
Run Code Online (Sandbox Code Playgroud)

这将生成FruitID所需类型的s 列表.

编辑:(回应下面的评论)

类型只有1或2但从不3

然后,您可以按如下方式简化查询:

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);
Run Code Online (Sandbox Code Playgroud)