gpt4 book ai didi

c# - linq查询选择特定值的所有元素但没有其他值

转载 作者:行者123 更新时间:2023-11-30 19:28:38 25 4
gpt4 key购买 nike

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

| FruitID | BasketID | FruitType |

我在查询中传递了一个 BasketIDs 列表,我想要 BasketID 中的 FruitIDs 列表仅限于特定的 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。

| 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 列表。

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

Type is only 1 or 2 but never 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);

关于c# - linq查询选择特定值的所有元素但没有其他值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14688625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com