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

时间:2013-02-04 14:18:26

标签: c# linq linq-to-sql

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

| FruitID | BasketID | FruitType |

我在查询中传递了BasketIDs的列表,我希望FruitIDs内的BasketID列表中只包含FruitTypevar TheQuery = (from a in MyDC.MyTable where TheBasketIDs.Contains(a.BasketID) && a.FruitType == 1 // need help here select a.FruitID).ToList(); (值只能是1或2)。

这就是我所拥有的:

where

我在表达第二个FruitIDs条件时遇到了一些困难。我希望FruitType所有| FruitID | BasketID | FruitType | | 23 | 2 | 1 | | 23 | 5 | 1 | | 19 | 2 | 1 | | 19 | 5 | 2 | 都是1,而且都不是2。

FruitType

例如,Fruit 23是正常的,因为它的FruitType总是1,但Fruit 19不合适,因为它的TheBasketIDs也是2,即使{{1}}的列表也是如此我传入的不包含5。

2 个答案:

答案 0 :(得分: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);

这将生成所需类型的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);

答案 1 :(得分:1)

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();
相关问题