繁体   English   中英

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

[英]linq query selecting all elements of certain value but none of another value

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

| FruitID | BasketID | FruitType |

我通过查询列表BasketIDs和我想的列表FruitIDs是内BasketID和只有在一定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();

我有一些难以表达的第二个where条件。 我想要FruitIDs ,其中所有FruitType都是1,没有2是2。

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

例如,Fruit 23没问题,因为它的FruitType总是1,但Fruit 19不好,因为它的FruitType也是2,即使我传入的TheBasketIDs列表中不包含5。

执行此操作的一种方法是按果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);

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

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

类型只有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);
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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM